package com.government.article.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.government.app.bo.KeywordSearchBO;
import com.government.app.bo.KeywordSearchDetailsBO;
import com.government.app.vo.AppOrgInfoVO;
import com.government.app.vo.KeywordSearchDetailsVO;
import com.government.app.vo.KeywordSearchVO;
import com.government.area.domain.ParkArea;
import com.government.area.mapper.ParkAreaMapper;
import com.government.article.bo.ArticlePolicyBO;
import com.government.article.bo.NormalPolicyBO;
import com.government.article.domain.Article;
import com.government.article.domain.ArticleInformation;
import com.government.article.domain.ArticlePolicyRel;
import com.government.article.mapper.ArticleInformationMapper;
import com.government.article.mapper.ArticleMapper;
import com.government.article.mapper.ArticlePolicyRelMapper;
import com.government.article.vo.*;
import com.government.common.core.domain.BaseTreeVo;
import com.government.common.core.domain.entity.SysDictData;
import com.government.common.core.domain.entity.SysUser;
import com.government.common.core.domain.model.LoginUser;
import com.government.common.exception.ServiceException;
import com.government.common.utils.*;
import com.government.company.domain.Company;
import com.government.company.domain.Industry;
import com.government.company.mapper.CompanyMapper;
import com.government.company.service.ICompanyService;
import com.government.item.bo.SelectItemByPolicyBO;
import com.government.item.domain.ExcelDetail;
import com.government.item.mapper.ExcelDetailMapper;
import com.government.member.domain.UserHobby;
import com.government.member.domain.UserPlan;
import com.government.member.mapper.UserHobbyMapper;
import com.government.member.mapper.UserPlanMapper;
import com.government.org.domain.OrgInfo;
import com.government.org.mapper.OrgInfoMapper;
import com.government.system.domain.WebUrl;
import com.government.system.domain.vo.WebAuthVo;
import com.government.system.mapper.WebUrlMapper;
import com.government.system.service.ISysConfigService;
import com.government.system.service.ISysDictTypeService;
import com.government.system.service.WebRoleAuthService;
import com.government.tag.domain.Tag;
import com.government.tag.mapper.TagMapper;
import org.apache.commons.compress.utils.Lists;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.government.article.mapper.ArticlePolicyMapper;
import com.government.article.domain.ArticlePolicy;
import com.government.article.service.IArticlePolicyService;

import static com.government.common.utils.PageUtils.startPage;
import static com.government.common.utils.SecurityUtils.getLoginUser;

/**
 * 政策分类信息Service业务层处理
 *
 * @author system
 * @date 2023-09-20
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ArticlePolicyServiceImpl implements IArticlePolicyService {
    @Autowired
    private ArticlePolicyMapper articlePolicyMapper;
    @Autowired
    private ArticlePolicyRelMapper articlePolicyRelMapper;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private UserHobbyMapper userHobbyMapper;
    @Autowired
    private TagMapper tagMapper;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private OrgInfoMapper orgInfoMapper;
    @Autowired
    private WebUrlMapper webUrlMapper;
    @Autowired
    private ParkAreaMapper parkAreaMapper;
    @Autowired
    private UserPlanMapper userPlanMapper;
    @Autowired
    private ICompanyService companyService;

    @Autowired
    private ISysDictTypeService dictTypeService;

    @Autowired
    private WebRoleAuthService webRoleAuthService;

    @Autowired
    private ArticleInformationMapper articleInformationMapper;
    @Autowired
    private ExcelDetailMapper excelDetailMapper;

    /**
     * 查询政策分类信息
     *
     * @param articleId 政策分类信息主键
     * @return 政策分类信息
     */
    @Override
    public ArticlePolicyVO selectArticlePolicyByArticleId(Long articleId) {
        ArticlePolicyVO articlePolicyVO = articlePolicyMapper.selectArticlePolicyByArticleId(articleId);
        if (StrUtil.isNotBlank(articlePolicyVO.getTag())) {
            articlePolicyVO.setTags(Arrays.asList(articlePolicyVO.getTag().split(",")));
        }
        if (StrUtil.isNotBlank(articlePolicyVO.getConnection())) {
            articlePolicyVO.setConnectionList(Arrays.asList(articlePolicyVO.getConnection().split(",")));
        }
        if (StrUtil.isNotBlank(articlePolicyVO.getPrePolicyYear())) {
            articlePolicyVO.setPrePolicyYearList(Arrays.asList(articlePolicyVO.getPrePolicyYear().split(",")));
        }
        if (StrUtil.isNotBlank(articlePolicyVO.getPrePolicyId())) {
            articlePolicyVO.setPrePolicyList(Arrays.asList(articlePolicyVO.getPrePolicyId().split(",")));
        }
        if (StrUtil.isNotBlank(articlePolicyVO.getEvolutionRel())) {
            articlePolicyVO.setEvolutionRelList(Arrays.asList(articlePolicyVO.getEvolutionRel().split(",")));
        }
        if (StrUtil.isNotBlank(articlePolicyVO.getWebUrl())) {
            articlePolicyVO.setWebUrlList(Arrays.asList(articlePolicyVO.getWebUrl().split(",")));
        }
        if (StrUtil.isNotBlank(articlePolicyVO.getIndustryId())) {
            articlePolicyVO.setIndustryIds(Arrays.asList(articlePolicyVO.getIndustryId().split(",")));
        }
        if (StrUtil.isNotBlank(articlePolicyVO.getDistrict())) {
            String[] parkAreaIdStr = articlePolicyVO.getDistrict().split(",");
            articlePolicyVO.setParkAreaIds(Arrays.asList(parkAreaIdStr));
        }
//        if (Objects.nonNull(articlePolicyVO.getCutOffTime())) {
//            articlePolicyVO.setCutOffTimeStr(DateUtil.formatDateTime(articlePolicyVO.getCutOffTime()));
//        }

        return articlePolicyVO;
    }

    @Override
    public List<ArticlePolicyVO> selectArticlePolicyList(ArticlePolicyBO bo) {
        return articlePolicyMapper.selectArticlePolicyList(bo);
    }

    @Override
    public List<AllPolicyVO> selectAllPolicy() {
        return articlePolicyMapper.selectAllPolicy();
    }

    @Override
    public List<BaseTreeVo> selectPolicyTree() {

        List<ArticlePolicy> policyList = articlePolicyMapper.selectPolicyTree();
        if (CollectionUtils.isEmpty(policyList)) {

            return null;
        }
        HashMap<Long, List<BaseTreeVo>> allNodeMap = new HashMap<>();

        for (ArticlePolicy item : policyList) {
            if (StrUtil.isNotBlank(item.getParentId()) && item.getParentId().contains(",")) {
                continue;
            }
            Long parentId = StrUtil.isBlank(item.getParentId()) ? 0 : Long.parseLong(item.getParentId());
            List<BaseTreeVo> nodeList = allNodeMap.get(parentId);
            if (CollectionUtils.isEmpty(nodeList)) {

                nodeList = Lists.newArrayList();
            }
            BaseTreeVo treeVO = new BaseTreeVo();
            treeVO.setId(String.valueOf(item.getArticleId()));
            treeVO.setValue(item.getArticleId());
            treeVO.setLabel(item.getName());
            nodeList.add(treeVO);
            allNodeMap.put(parentId, nodeList);
        }
        List<BaseTreeVo> rootNode = allNodeMap.get(0L);

        return TreeUtils.buildTree(rootNode, allNodeMap);
    }

    /**
     * 搜索政策分类信息列表
     *
     * @param bo 政策分类信息
     * @return 政策分类信息
     */
    @Override
    public List<KeywordSearchVO> searchArticlePolicyList(KeywordSearchBO bo) {
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser currentUser = null;
        if (StringUtils.isNotNull(loginUser)) {
            currentUser = loginUser.getUser();

        }
        List<Tag> tagList = tagMapper.selectList(Wrappers.lambdaQuery());
        Map<String, Long> tagNamesMap = tagList.stream().collect(Collectors.toMap(Tag::getName, Tag::getId));
        List<String> tagIds = Lists.newArrayList();
        // 项目类型标签
        if (CollUtil.isNotEmpty(bo.getItemTypes())) {
            for (String itemType : bo.getItemTypes()) {
                Long tagId = tagNamesMap.get(itemType);
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            }
        }
        // 主管部门标签
        if (CollUtil.isNotEmpty(bo.getOrgTypes())) {
            for (String orgType : bo.getOrgTypes()) {
                Long tagId = tagNamesMap.get(orgType);
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            }
        }
        bo.setTagIds(tagIds);

        startPage();
        List<KeywordSearchVO> result = articlePolicyMapper.searchArticlePolicyList(bo);
        List<SysDictData> itemTypeList = dictTypeService.selectDictDataByType("item_type");
        Map<String, String> itemTypeMap = itemTypeList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        for (KeywordSearchVO item : result) {
            if ("有效".equals(item.getStatus())) {
                if (Objects.nonNull(item.getCutOffTime())) {
                    if (DateUtil.compare(new Date(), item.getCutOffTime()) < 0) {
                        item.setStatus("申报中");
                    }
                }
            }
            if (Objects.nonNull(currentUser)) {

                int likeFlag = userHobbyMapper.selectCount(Wrappers.<UserHobby>lambdaQuery().eq(UserHobby::getUserId, currentUser.getUserId()).eq(UserHobby::getSourceId, item.getId()).eq(UserHobby::getType, "1").eq(UserHobby::getSourceType, "2"));
                int collectFlag = userHobbyMapper.selectCount(Wrappers.<UserHobby>lambdaQuery().eq(UserHobby::getUserId, currentUser.getUserId()).eq(UserHobby::getSourceId, item.getId()).eq(UserHobby::getType, "2").eq(UserHobby::getSourceType, "2"));
                item.setIsLike(String.valueOf(likeFlag));
                item.setIsCollect(String.valueOf(collectFlag));
            }

            if (Objects.nonNull(item.getOrgId())) {
                OrgInfo orgInfo = orgInfoMapper.selectOrgInfoByOrgId(item.getOrgId());
                if (Objects.nonNull(orgInfo)) {
                    item.setOrgName(orgInfo.getOrgName());
                }
            }
            item.setItemTypeId(item.getItemType());
            item.setItemType(itemTypeMap.get(item.getItemType()));
        }

        return result;
    }

    /**
     * 查询政策分类信息列表
     *
     * @param bo 政策分类信息
     * @return 政策分类信息
     */
    @Override
    public KeywordSearchDetailsVO selectArticlePolicyDetails(KeywordSearchDetailsBO bo) {

        String authorization = ServletUtils.getRequest().getHeader("Authorization");
        SysUser currentUser = null;
        if (StrUtil.isNotBlank(authorization)) {
            // 获取当前的用户
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (StringUtils.isNotNull(loginUser)) {
                currentUser = loginUser.getUser();

            }
        }
        KeywordSearchDetailsVO result = articlePolicyMapper.selectArticlePolicyDetails(bo);
        List<String> quotaList = Lists.newArrayList();
        if (StrUtil.isNotBlank(result.getQuota1())) {
            quotaList.add(result.getQuota1());
        }
        if (StrUtil.isNotBlank(result.getQuota2())) {
            quotaList.add(result.getQuota2());
        }
        if (CollUtil.isNotEmpty(quotaList)) {
            result.setQuota(String.join("-", quotaList));
        }
        if ("有效".equals(result.getStatus())) {
            if (Objects.nonNull(result.getCutOffTime())) {
                if (DateUtil.compare(new Date(), result.getCutOffTime()) < 0) {
                    result.setStatus("申报中");
                }
            }
        }
        List<AppOrgInfoVO> appOrgInfoList = Lists.newArrayList();
        if (StrUtil.isNotBlank(result.getOrgId())) {
//            result.setOrgName(result.getOrgName());
            AppOrgInfoVO appOrgInfoVO = new AppOrgInfoVO();
            appOrgInfoVO.setOrgId(result.getOrgId());
            appOrgInfoVO.setOrgName(result.getOrgName());
            appOrgInfoList.add(appOrgInfoVO);
            result.setOrgInfoList(appOrgInfoList);
            result.setOrgName("<a href='http://www.touce.com.cn/detail?id=" + result.getOrgId() + "&searchType=3' style='font-size:14px;' target='_blank'>" + result.getOrgName() + "</a>");
        }
        if (StrUtil.isNotBlank(result.getWebUrl())) {
            List<WebUrl> webUrlList = webUrlMapper.selectList(Wrappers.<WebUrl>lambdaQuery().select(WebUrl::getId, WebUrl::getName, WebUrl::getUrl));
            Map<Long, WebUrl> webUrlMap = webUrlList.stream().collect(Collectors.toMap(WebUrl::getId, x -> x));
            String[] webUrls = result.getWebUrl().split(",");
            List<String> systemNameList = Lists.newArrayList();
            for (String webUrl : webUrls) {
                systemNameList.add("<a href='" + webUrlMap.get(Long.parseLong(webUrl)).getUrl() + "' style='font-size:14px;' target='_blank'>" + webUrlMap.get(Long.parseLong(webUrl)).getName() + "</a>");
//                systemNameList.add(webUrlMap.get(Long.parseLong(webUrl)).getName());
            }
            result.setSystemName(String.join(",", systemNameList));
        }

        String parkNameStr = result.getParkName1();
        if (StrUtil.isNotBlank(result.getParkName2())) {
            parkNameStr += "-" + result.getParkName2();
        }
        if (StrUtil.isNotBlank(result.getParkName3())) {
            parkNameStr += "-" + result.getParkName3();
        }
        if (StrUtil.isNotBlank(result.getParkName4())) {
            parkNameStr += "-" + result.getParkName4();
        }
        if (StrUtil.isNotBlank(result.getParkName5())) {
            parkNameStr += "-" + result.getParkName5();
        }
        if (StrUtil.isNotBlank(result.getParkName6())) {
            parkNameStr += "-" + result.getParkName6();
        }
        result.setAreaName(parkNameStr);

        if (Objects.nonNull(currentUser)) {
            int likeFlag = userHobbyMapper.selectCount(Wrappers.<UserHobby>lambdaQuery().eq(UserHobby::getUserId, currentUser.getUserId()).eq(UserHobby::getSourceId, result.getId()).eq(UserHobby::getType, "1").eq(UserHobby::getSourceType, "2"));
            int collectFlag = userHobbyMapper.selectCount(Wrappers.<UserHobby>lambdaQuery().eq(UserHobby::getUserId, currentUser.getUserId()).eq(UserHobby::getSourceId, result.getId()).eq(UserHobby::getType, "2").eq(UserHobby::getSourceType, "2"));
            result.setIsLike(String.valueOf(likeFlag));
            result.setIsCollect(String.valueOf(collectFlag));
        }
        return result;
    }

    /**
     * 新增政策分类信息
     *
     * @param bo 政策分类信息
     * @return 结果
     */
    @Override
    public int insertArticlePolicy(ArticlePolicyBO bo) {

        SysUser user = getLoginUser().getUser();

        Article article = new Article();

        ArticlePolicy articlePolicy = new ArticlePolicy();
        articlePolicy.setBenefits(bo.getBenefits());
        articlePolicy.setStatus(bo.getStatus());
        articlePolicy.setParentId(bo.getParentId());
        if (CollUtil.isNotEmpty(bo.getConnectionList())) {
            articlePolicy.setConnection(String.join(",", bo.getConnectionList()));
        } else {
            articlePolicy.setConnection("");
        }
        if (CollUtil.isNotEmpty(bo.getPrePolicyYearList())) {
            articlePolicy.setPrePolicyYear(String.join(",", bo.getPrePolicyYearList()));
        } else {
            articlePolicy.setPrePolicyYear("");
        }
        if (CollUtil.isNotEmpty(bo.getPrePolicyList())) {
            articlePolicy.setPrePolicyId(String.join(",", bo.getPrePolicyList()));
        } else {
            articlePolicy.setPrePolicyId("");
        }
        if (Objects.nonNull(bo.getCutOffTime())) {
            articlePolicy.setCutOffTime(DateUtil.offsetHour(bo.getCutOffTime(), 17));
        }
//        articlePolicy.setSystemWeb1(bo.getSystemWeb1());
//        articlePolicy.setSystemName1(bo.getSystemName1());
//        articlePolicy.setSystemWeb2(bo.getSystemWeb2());
//        articlePolicy.setSystemName2(bo.getSystemName2());
//        articlePolicy.setSystemWeb3(bo.getSystemWeb3());
//        articlePolicy.setSystemName3(bo.getSystemName3());
//        List<String> webList = Lists.newArrayList();
//
//        if (StrUtil.isNotBlank(articlePolicy.getSystemWeb1())) {
//            webList.add(articlePolicy.getSystemWeb1() + "-" + articlePolicy.getSystemName1());
//        }
//        if (StrUtil.isNotBlank(articlePolicy.getSystemWeb2())) {
//            webList.add(articlePolicy.getSystemWeb2() + "-" + articlePolicy.getSystemName2());
//        }
//        if (StrUtil.isNotBlank(articlePolicy.getSystemWeb3())) {
//            webList.add(articlePolicy.getSystemWeb3() + "-" + articlePolicy.getSystemName3());
//        }

//        if (CollUtil.isNotEmpty(webList)) {
//            for (String str : webList) {
//                String[] webs = str.split("-");
//                int count = webUrlMapper.selectCount(Wrappers.<WebUrl>lambdaQuery().eq(WebUrl::getUrl, webs[0]));
//                if (count == 0) {
//                    WebUrl webUrl = new WebUrl();
//                    webUrl.setUrl(webs[0]);
//                    webUrl.setName(webs[1]);
//                    webUrl.setCreateTime(new Date());
//                    webUrl.setCreateBy(String.valueOf(user.getUserId()));
//                    webUrlMapper.insert(webUrl);
//                }
//            }
//        }
        articlePolicy.setYear(bo.getYear());
        articlePolicy.setName(bo.getName());
        articlePolicy.setFormerName(bo.getFormerName());
        articlePolicy.setQuota1(bo.getQuota1());
        articlePolicy.setQuota2(bo.getQuota2());
        articlePolicy.setOrgId(bo.getOrgId());
        if (Objects.nonNull(bo.getOrgId())) {
            OrgInfo orgInfo = orgInfoMapper.selectOrgInfoByOrgId(bo.getOrgId());
            articlePolicy.setOrgType(orgInfo.getOrgType());
        }

        // 园区数据处理
        parkAreaHandler(bo, articlePolicy);

        articlePolicy.setManageRel(bo.getManageRel());
        articlePolicy.setEvolutionRel(bo.getEvolutionRel());
        articlePolicy.setRelType(bo.getRelType());
        articlePolicy.setSupportRange(bo.getSupportRange());
        articlePolicy.setIntro(bo.getIntro());
        articlePolicy.setIsPublish(bo.getIsPublish());
        articlePolicy.setItemType(bo.getItemType());
        articlePolicy.setItemGrade(bo.getItemGrade());
        articlePolicy.setItemLevel(bo.getItemLevel());
        articlePolicy.setCorrespondence(bo.getCorrespondence());
        articlePolicy.setIsRedeclaration(bo.getIsRedeclaration());

        article.setStstus("0");
        if ("1".equals(bo.getIsPublish())) {
            articlePolicy.setPublishTime(new Date());
            article.setAuditBy(String.valueOf(user.getUserId()));
            article.setAuditTime(new Date());
            article.setStstus("1");
        }

        if (CollUtil.isNotEmpty(bo.getIndustryIds())) {
            articlePolicy.setIndustryId("," + String.join(",", bo.getIndustryIds()));
        }
        // 排序处理
        policySortHandler(articlePolicy);
        if (CollUtil.isNotEmpty(bo.getTags())) {

            articlePolicy.setTag(String.join(",", bo.getTags()));
        }

        if (CollUtil.isNotEmpty(bo.getEvolutionRelList())) {
            articlePolicy.setEvolutionRel(String.join(",", bo.getEvolutionRelList()));
        }

        if (CollUtil.isNotEmpty(bo.getWebUrlList())) {
            articlePolicy.setWebUrl(String.join(",", bo.getWebUrlList()));
        }

        article.setTitle(bo.getName());
        article.setContent(bo.getIntro());
        article.setType(63L);
        article.setTypeName("政策分类");
        article.setCreateTime(DateUtils.getNowDate());
        article.setCreateBy(String.valueOf(user.getUserId()));
        article.setUpdateBy(String.valueOf(user.getUserId()));
        article.setUpdateTime(new Date());
        articleMapper.insert(article);

        // 关联政策关系处理
        if (CollUtil.isNotEmpty(bo.getConnectionList())) {
            articlePolicy.setConnection(String.join(",", bo.getConnectionList()));
            List<ArticlePolicy> connectionPolicyList = articlePolicyMapper.selectList(Wrappers.<ArticlePolicy>lambdaQuery().in(ArticlePolicy::getArticleId, bo.getConnectionList()));
            for (ArticlePolicy item : connectionPolicyList) {
                if (StrUtil.isBlank(item.getConnection())) {
                    item.setConnection(String.valueOf(article.getArticleId()));
                } else {
                    String[] connectionId = item.getConnection().split(",");
                    List<String> connectionStrIds = new ArrayList<String>(Arrays.asList(connectionId));
                    connectionStrIds.add(String.valueOf(article.getArticleId()));
                    item.setConnection(String.join(",", connectionStrIds));
                }
                articlePolicyMapper.updateById(item);
            }
        }
        articlePolicy.setUpdateBy(String.valueOf(user.getUserId()));
        articlePolicy.setUpdateTime(new Date());
        articlePolicy.setCreateBy(String.valueOf(user.getUserId()));
        articlePolicy.setCreateTime(DateUtils.getNowDate());
        articlePolicy.setArticleId(article.getArticleId());

        // 处理项目等级
//        if (StrUtil.isBlank(articlePolicy.getParentId())) {
//            articlePolicy.setItemGrade("1");
//        } else {
        if (StrUtil.isNotBlank(articlePolicy.getParentId())) {
            ArticlePolicy parentPolicy = articlePolicyMapper.selectById(articlePolicy.getParentId());
            if (StrUtil.isNotBlank(parentPolicy.getParentId())) {
                if (StrUtil.isNotBlank(parentPolicy.getItemGrade())) {
                    articlePolicy.setItemGrade(String.valueOf(Integer.parseInt(parentPolicy.getItemGrade()) + 1));
                }
            }
        }
//        }

        // 处理子级政策数据
        if (StrUtil.isBlank(articlePolicy.getParentId()) &&
                (articlePolicy.getName().contains("地方推荐")
                        || articlePolicy.getName().contains("地方管理") || articlePolicy.getName().contains("地方切块"))) {
            manageChildHandler(articlePolicy);
        }


        return articlePolicyMapper.insert(articlePolicy);

    }

    public List<WebUrl> getWebUrlList() {
        return webUrlMapper.selectList(Wrappers.lambdaQuery());
    }

    private void parkAreaHandler(ArticlePolicyBO bo, ArticlePolicy articlePolicy) {
        if (CollUtil.isNotEmpty(bo.getParkAreaIds())) {
            List<ParkArea> parkAreaList = parkAreaMapper.selectList(Wrappers.<ParkArea>lambdaQuery());
            Map<Long, String> parkAreaMap = parkAreaList.stream().collect(Collectors.toMap(ParkArea::getId, ParkArea::getName));
//
//        articlePolicy.setPark1(orgInfo.getPark1());
//        articlePolicy.setParkName1(orgInfo.getParkName1());
//        articlePolicy.setPark2(orgInfo.getPark2());
//        articlePolicy.setParkName2(orgInfo.getParkName2());
//        articlePolicy.setPark3(orgInfo.getPark3());
//        articlePolicy.setParkName3(orgInfo.getParkName3());
//        articlePolicy.setPark4(orgInfo.getPark4());
//        articlePolicy.setParkName4(orgInfo.getParkName4());
//        articlePolicy.setPark5(orgInfo.getPark5());
//        articlePolicy.setParkName5(orgInfo.getParkName5());
//        articlePolicy.setPark6(orgInfo.getPark6());
//        articlePolicy.setParkName6(orgInfo.getParkName6());
//        articlePolicy.setLastPark(orgInfo.getLastPark());
//        articlePolicy.setLastParkName(orgInfo.getLastParkName());
//        articlePolicy.setDistrict(orgInfo.getArea());
            if (bo.getParkAreaIds().size() > 0) {
                Long park1 = Long.parseLong(bo.getParkAreaIds().get(0));
                articlePolicy.setPark1(park1);
                articlePolicy.setLastPark(park1);
                articlePolicy.setParkName1(parkAreaMap.get(park1));
                articlePolicy.setLastParkName(parkAreaMap.get(park1));
            }
            if (bo.getParkAreaIds().size() > 1) {
                Long park2 = Long.parseLong(bo.getParkAreaIds().get(1));
                articlePolicy.setPark2(park2);
                articlePolicy.setLastPark(park2);
                articlePolicy.setParkName2(parkAreaMap.get(park2));
                articlePolicy.setLastParkName(parkAreaMap.get(park2));
            }
            if (bo.getParkAreaIds().size() > 2) {
                Long park3 = Long.parseLong(bo.getParkAreaIds().get(2));
                articlePolicy.setPark3(park3);
                articlePolicy.setLastPark(park3);
                articlePolicy.setParkName3(parkAreaMap.get(park3));
                articlePolicy.setLastParkName(parkAreaMap.get(park3));
            }
            if (bo.getParkAreaIds().size() > 3) {
                Long park4 = Long.parseLong(bo.getParkAreaIds().get(3));
                articlePolicy.setPark4(park4);
                articlePolicy.setLastPark(park4);
                articlePolicy.setParkName4(parkAreaMap.get(park4));
                articlePolicy.setLastParkName(parkAreaMap.get(park4));
            }
            if (bo.getParkAreaIds().size() > 4) {
                Long park5 = Long.parseLong(bo.getParkAreaIds().get(4));
                articlePolicy.setPark5(park5);
                articlePolicy.setLastPark(park5);
                articlePolicy.setParkName5(parkAreaMap.get(park5));
                articlePolicy.setLastParkName(parkAreaMap.get(park5));
            }
            if (bo.getParkAreaIds().size() > 5) {
                Long park6 = Long.parseLong(bo.getParkAreaIds().get(5));
                articlePolicy.setPark6(park6);
                articlePolicy.setLastPark(park6);
                articlePolicy.setParkName6(parkAreaMap.get(park6));
                articlePolicy.setLastParkName(parkAreaMap.get(park6));
            }
            articlePolicy.setDistrict(String.join(",", bo.getParkAreaIds()));
        }

    }

    private void policySortHandler(ArticlePolicy articlePolicy) {

        if (StrUtil.isNotBlank(articlePolicy.getOrgType())) {
            if ("14".equals(articlePolicy.getOrgType())) {//科技
                articlePolicy.setSort1(1);
            } else if ("9".equals(articlePolicy.getOrgType())) {//工信
                articlePolicy.setSort1(20);
            } else if ("8".equals(articlePolicy.getOrgType())) {// 发改
                articlePolicy.setSort1(40);
            } else if ("27".equals(articlePolicy.getOrgType())) {// 市场
                articlePolicy.setSort1(60);
            } else if ("16".equals(articlePolicy.getOrgType())) {// 人社
                articlePolicy.setSort1(80);
            } else if ("22".equals(articlePolicy.getOrgType())) {// 农业
                articlePolicy.setSort1(100);
            } else if ("17".equals(articlePolicy.getOrgType())) {// 商务
                articlePolicy.setSort1(120);
            } else if ("15".equals(articlePolicy.getOrgType())) {// 财政
                articlePolicy.setSort1(140);
            } else if ("18".equals(articlePolicy.getOrgType())) {// 环境
                articlePolicy.setSort1(160);
            } else if ("28".equals(articlePolicy.getOrgType())) {// 交通
                articlePolicy.setSort1(180);
            } else if ("23".equals(articlePolicy.getOrgType())) {// 文旅
                articlePolicy.setSort1(200);
            } else if ("24".equals(articlePolicy.getOrgType())) {// 教育
                articlePolicy.setSort1(220);
            } else if ("29".equals(articlePolicy.getOrgType())) {// 住建
                articlePolicy.setSort1(240);
            } else if ("21".equals(articlePolicy.getOrgType())) {// 金融
                articlePolicy.setSort1(260);
            } else if ("25".equals(articlePolicy.getOrgType())) {// 其他
                articlePolicy.setSort1(280);
            }
        }

        if (StrUtil.isNotBlank(articlePolicy.getItemGrade())) if ("1".equals(articlePolicy.getItemGrade())) { //国家级
            articlePolicy.setSort2(1);
        } else if ("2".equals(articlePolicy.getItemGrade())) { //省部级
            articlePolicy.setSort2(20);
        } else if ("3".equals(articlePolicy.getItemGrade())) { //地市级
            articlePolicy.setSort2(40);
        } else if ("4".equals(articlePolicy.getItemGrade())) { //区县级
            articlePolicy.setSort2(60);
        }

        if (StrUtil.isNotBlank(articlePolicy.getItemLevel())) {
            if ("1".equals(articlePolicy.getItemLevel())) { //一级
                articlePolicy.setSort3(1);
            } else if ("2".equals(articlePolicy.getItemLevel())) { //二级
                articlePolicy.setSort3(20);
            } else if ("3".equals(articlePolicy.getItemLevel())) { //三级
                articlePolicy.setSort3(40);
            } else if ("4".equals(articlePolicy.getItemLevel())) { //四级
                articlePolicy.setSort3(60);
            }
        }
    }

    /**
     * 修改政策分类信息
     *
     * @param bo 政策分类信息
     * @return 结果
     */
    @Override
    public int updateArticlePolicy(ArticlePolicyBO bo) {

        SysUser user = getLoginUser().getUser();

        Article article = articleMapper.selectById(bo.getArticleId());
        ServiceException.throwExOnCondition(Objects.isNull(article), "政策不存在");

        ArticlePolicy articlePolicy = articlePolicyMapper.selectById(bo.getArticleId());
        articlePolicy.setBenefits(bo.getBenefits());
        articlePolicy.setParentId(bo.getParentId());
        articlePolicy.setStatus(bo.getStatus());
        if (CollUtil.isNotEmpty(bo.getPrePolicyYearList())) {
            articlePolicy.setPrePolicyYear(String.join(",", bo.getPrePolicyYearList()));
        } else {
            articlePolicy.setPrePolicyYear("");
        }
        if (CollUtil.isNotEmpty(bo.getConnectionList())) {
            articlePolicy.setConnection(String.join(",", bo.getConnectionList()));
        } else {
            articlePolicy.setConnection("");
        }
        if (CollUtil.isNotEmpty(bo.getPrePolicyList())) {
            articlePolicy.setPrePolicyId(String.join(",", bo.getPrePolicyList()));
        } else {
            articlePolicy.setPrePolicyId("");
        }

        if (Objects.nonNull(bo.getCutOffTime())) {
            articlePolicy.setCutOffTime(DateUtil.offsetHour(bo.getCutOffTime(), 17));
        } else {
            articlePolicy.setCutOffTime(null);
        }
        if ("1".equals(bo.getIsPublish())) {
            articlePolicy.setPublishTime(new Date());
            article.setAuditBy(String.valueOf(user.getUserId()));
            article.setAuditTime(new Date());
            article.setStstus("1");
        }

//        articlePolicy.setSystemWeb1(bo.getSystemWeb1());
//        articlePolicy.setSystemName1(bo.getSystemName1());
//        articlePolicy.setSystemWeb2(bo.getSystemWeb2());
//        articlePolicy.setSystemName2(bo.getSystemName2());
//        articlePolicy.setSystemWeb3(bo.getSystemWeb3());
//        articlePolicy.setSystemName3(bo.getSystemName3());
//        List<String> webList = Lists.newArrayList();
//
//        if (StrUtil.isNotBlank(articlePolicy.getSystemWeb1())) {
//            webList.add(articlePolicy.getSystemWeb1() + "-" + articlePolicy.getSystemName1());
//        }
//        if (StrUtil.isNotBlank(articlePolicy.getSystemWeb2())) {
//            webList.add(articlePolicy.getSystemWeb2() + "-" + articlePolicy.getSystemName2());
//        }
//        if (StrUtil.isNotBlank(articlePolicy.getSystemWeb3())) {
//            webList.add(articlePolicy.getSystemWeb3() + "-" + articlePolicy.getSystemName3());
//        }
//
//        if (CollUtil.isNotEmpty(webList)) {
//            for (String str : webList) {
//                String[] webs = str.split("-");
//                int count = webUrlMapper.selectCount(Wrappers.<WebUrl>lambdaQuery().eq(WebUrl::getUrl, webs[0]));
//                if (count == 0) {
//                    WebUrl webUrl = new WebUrl();
//                    webUrl.setUrl(webs[0]);
//                    webUrl.setName(webs[1]);
//                    webUrl.setCreateTime(new Date());
//                    webUrl.setCreateBy(String.valueOf(user.getUserId()));
//                    webUrlMapper.insert(webUrl);
//                }
//            }
//        }
        articlePolicy.setYear(bo.getYear());
        articlePolicy.setName(bo.getName());
        articlePolicy.setFormerName(bo.getFormerName());
        articlePolicy.setQuota1(bo.getQuota1());
        articlePolicy.setQuota2(bo.getQuota2());
        articlePolicy.setOrgId(bo.getOrgId());
        if (Objects.nonNull(bo.getOrgId())) {
            OrgInfo orgInfo = orgInfoMapper.selectOrgInfoByOrgId(bo.getOrgId());
            if (Objects.nonNull(orgInfo)) {
                articlePolicy.setOrgType(orgInfo.getOrgType());
            }
        }
        // 园区数据处理
        parkAreaHandler(bo, articlePolicy);
        articlePolicy.setManageRel(bo.getManageRel());
        articlePolicy.setEvolutionRel(bo.getEvolutionRel());
        articlePolicy.setRelType(bo.getRelType());
        articlePolicy.setSupportRange(bo.getSupportRange());
        articlePolicy.setIntro(bo.getIntro());
        articlePolicy.setIsPublish(bo.getIsPublish());
        articlePolicy.setItemType(bo.getItemType());
        articlePolicy.setItemGrade(bo.getItemGrade());
        articlePolicy.setItemLevel(bo.getItemLevel());
        articlePolicy.setCorrespondence(bo.getCorrespondence());
        articlePolicy.setIsRedeclaration(bo.getIsRedeclaration());

        if (CollUtil.isNotEmpty(bo.getIndustryIds())) {
            articlePolicy.setIndustryId("," + String.join(",", bo.getIndustryIds()));
        } else {
            articlePolicy.setIndustryId("");
        }

        // 排序处理
        policySortHandler(articlePolicy);
        if (CollUtil.isNotEmpty(bo.getTags())) {
            articlePolicy.setTag(String.join(",", bo.getTags()));
        } else {
            articlePolicy.setTag("");
        }
        // 关联政策处理
        connectionPolicyHandler(bo, article, articlePolicy);
        if (CollUtil.isNotEmpty(bo.getEvolutionRelList())) {
            articlePolicy.setEvolutionRel(String.join(",", bo.getEvolutionRelList()));
        } else {
            articlePolicy.setEvolutionRel("");
        }

        if (CollUtil.isNotEmpty(bo.getWebUrlList())) {
            articlePolicy.setWebUrl(String.join(",", bo.getWebUrlList()));
        } else {
            articlePolicy.setWebUrl("");
        }

        articlePolicy.setUpdateTime(DateUtils.getNowDate());

        // 处理项目等级
//        if (StrUtil.isBlank(articlePolicy.getParentId())) {
//            articlePolicy.setItemGrade("1");
//        } else {
        if (StrUtil.isNotBlank(articlePolicy.getParentId())) {
            ArticlePolicy parentPolicy = articlePolicyMapper.selectById(articlePolicy.getParentId());
            if (StrUtil.isNotBlank(parentPolicy.getParentId())) {
                if (StrUtil.isNotBlank(parentPolicy.getItemGrade())) {
                    articlePolicy.setItemGrade(String.valueOf(Integer.parseInt(parentPolicy.getItemGrade()) + 1));
                }
            }
        }

        // 处理子级政策数据
        if (StrUtil.isBlank(articlePolicy.getManageRel()) &&
                (articlePolicy.getName().contains("地方推荐")
                        || articlePolicy.getName().contains("地方管理") || articlePolicy.getName().contains("地方切块"))) {
            manageChildHandler(articlePolicy);
        }

        childHandler(articlePolicy);

        parentHandler(articlePolicy);

        articlePolicyMapper.updateById(articlePolicy);

        article.setTitle(bo.getName());
        article.setContent(bo.getIntro());
        article.setUpdateTime(DateUtils.getNowDate());
        article.setUpdateBy(String.valueOf(user.getUserId()));
        return articleMapper.updateById(article);

    }

    private void manageChildHandler(ArticlePolicy articlePolicy) {

        ArticlePolicy item = articlePolicyMapper.selectOne(Wrappers.<ArticlePolicy>lambdaQuery()
                .eq(ArticlePolicy::getManageRel, articlePolicy.getArticleId()));
        if (Objects.nonNull(item)) {
            item.setItemLevel(articlePolicy.getItemLevel());
            item.setCorrespondence(articlePolicy.getCorrespondence());
            item.setIsRedeclaration(articlePolicy.getIsRedeclaration());
            item.setYear(articlePolicy.getYear());
            item.setStatus(articlePolicy.getStatus());
            item.setWebUrl(articlePolicy.getWebUrl());
//            item.setSystemWeb1(articlePolicy.getSystemWeb1());
//            item.setSystemName1(articlePolicy.getSystemName1());
//            item.setSystemWeb2(articlePolicy.getSystemWeb2());
//            item.setSystemName2(articlePolicy.getSystemName2());
//            item.setSystemWeb3(articlePolicy.getSystemWeb3());
//            item.setSystemName3(articlePolicy.getSystemName3());
            String name = "";
            if (articlePolicy.getName().contains("（地方推荐")) {
                name = articlePolicy.getName().substring(0, articlePolicy.getName().indexOf("（地方推荐"));
                item.setName(name + item.getName().substring(item.getName().indexOf("（地方推荐")));
            } else if (articlePolicy.getName().contains("（地方管理")) {
                name = articlePolicy.getName().substring(0, articlePolicy.getName().indexOf("（地方管理"));
                item.setName(name + item.getName().substring(item.getName().indexOf("（地方管理")));
            } else if (articlePolicy.getName().contains("（地方切块")) {
                name = articlePolicy.getName().substring(0, articlePolicy.getName().indexOf("（地方切块"));
                item.setName(name + item.getName().substring(item.getName().indexOf("（地方切块")));
            }
            articlePolicyMapper.updateById(item);
            manageChildHandler(item);
        }
    }

    private void childHandler(ArticlePolicy articlePolicy) {

        if ("1".equals(articlePolicy.getItemType())
                || "2".equals(articlePolicy.getItemType())
                || "3".equals(articlePolicy.getItemType())
                || "4".equals(articlePolicy.getItemType())) {
            List<ArticlePolicy> policyList = articlePolicyMapper.selectList(Wrappers.<ArticlePolicy>lambdaQuery()
                    .eq(ArticlePolicy::getParentId, articlePolicy.getArticleId()));
            if (CollUtil.isNotEmpty(policyList)) {
                for (ArticlePolicy policy : policyList) {
                    policy.setItemGrade(String.valueOf(Integer.parseInt(articlePolicy.getItemGrade()) + 1));
                    policy.setStatus(articlePolicy.getStatus());
                    articlePolicyMapper.updateById(policy);
                    childHandler(policy);
                }
            }
        }
    }

    private void parentHandler(ArticlePolicy articlePolicy) {

        if ("1".equals(articlePolicy.getItemType())
                || "2".equals(articlePolicy.getItemType())
                || "3".equals(articlePolicy.getItemType())
                || "4".equals(articlePolicy.getItemType())) {
            if ("1".equals(articlePolicy.getStatus())) {
                ArticlePolicy parentPolicy = articlePolicyMapper.selectById(articlePolicy.getParentId());
                if (Objects.nonNull(parentPolicy)) {
//                    parentPolicy.setItemGrade(String.valueOf(Integer.parseInt(articlePolicy.getItemGrade()) + 1));
                    parentPolicy.setStatus(articlePolicy.getStatus());
                    articlePolicyMapper.updateById(parentPolicy);
                    if (StrUtil.isNotBlank(parentPolicy.getParentId())) {
                        parentHandler(parentPolicy);
                    }
                }
            }
        }
    }

    private void connectionPolicyHandler(ArticlePolicyBO bo, Article article, ArticlePolicy articlePolicy) {
        if (CollUtil.isNotEmpty(bo.getConnectionList())) {

            // 当前关联政策集合
            List<ArticlePolicy> currentConnectionPolicyList = articlePolicyMapper.selectList(Wrappers.<ArticlePolicy>lambdaQuery().in(ArticlePolicy::getArticleId, bo.getConnectionList()));
            // 历史关联政策集合
            List<String> historyConnectionPolicyIdList = Lists.newArrayList();
            String historyConnectionPolicyIdStr = articlePolicy.getConnection();
            if (StrUtil.isNotBlank(historyConnectionPolicyIdStr)) {
                String[] historyConnectionPolicyIds = historyConnectionPolicyIdStr.split(",");
                historyConnectionPolicyIdList = Arrays.asList(historyConnectionPolicyIds);

                // 找出取消关联的政策处理
                for (String historyConnectionPolicyId : historyConnectionPolicyIdList) {
                    if (StrUtil.isNotBlank(historyConnectionPolicyId)) {
                        if (!bo.getConnectionList().contains(historyConnectionPolicyId)) {
                            ArticlePolicy cancelPolicy = articlePolicyMapper.selectById(historyConnectionPolicyId);
                            List<String> cancelConnectionPolicyIdList = Arrays.asList(cancelPolicy.getConnection().split(","));
                            cancelConnectionPolicyIdList = cancelConnectionPolicyIdList.stream().filter(item -> !item.equals(String.valueOf(articlePolicy.getArticleId()))).collect(Collectors.toList());
                            cancelPolicy.setConnection(String.join(",", cancelConnectionPolicyIdList));
                            articlePolicyMapper.updateById(cancelPolicy);
                        }
                    }
                }
            }

            for (ArticlePolicy item : currentConnectionPolicyList) {
                if (StrUtil.isBlank(item.getConnection())) {
                    item.setConnection(String.valueOf(articlePolicy.getArticleId()));
                } else {
                    String[] connectionId = item.getConnection().split(",");
                    List<String> connectionStrIds = new ArrayList<String>(Arrays.asList(connectionId));
                    // 如果之前关联过，不再关联
                    if (connectionStrIds.contains(String.valueOf(articlePolicy.getArticleId()))) {
                        continue;
                    }
                    connectionStrIds.add(String.valueOf(article.getArticleId()));
                    item.setConnection(String.join(",", connectionStrIds));
                }

                articlePolicyMapper.updateById(item);
            }
            articlePolicy.setConnection(String.join(",", bo.getConnectionList()));
        }
    }

    /**
     * 删除政策分类信息信息
     *
     * @param articleId 政策分类信息主键
     * @return 结果
     */
    @Override
    public void deleteArticlePolicyByArticleId(Long[] articleIds) {
        for (Long articleId : articleIds) {
            Article article = articleMapper.selectById(articleId);
            article.setIsDeleted("1");
            article.setUpdateTime(new Date());
            article.setUpdateBy(String.valueOf(getLoginUser().getUserId()));

            ArticlePolicy articlePolicy = articlePolicyMapper.selectById(articleId);
            articlePolicy.setIsDeleted("1");
            articlePolicy.setUpdateTime(new Date());
            articlePolicy.setUpdateBy(String.valueOf(getLoginUser().getUserId()));
            articlePolicyMapper.updateById(articlePolicy);
            articleMapper.updateById(article);

            excelDetailMapper.deleteItemByPolicyId(articlePolicy.getArticleId());
        }
    }

    @Override
    public void copyArticlePolicyByArticleId(Long articleId) {

        Article article = articleMapper.selectById(articleId);
        article.setArticleId(null);

        articleMapper.insert(article);

        ArticlePolicy articlePolicy = articlePolicyMapper.selectById(articleId);
        articlePolicy.setArticleId(article.getArticleId());
        articlePolicyMapper.insert(articlePolicy);
    }

    /**
     * 根据资讯id查询所属政策树
     *
     * @param articleId
     * @return
     */
    @Override
    public List<PolicyTreeVO> getRelationPolicy(Long articleId) {


        List<ArticlePolicyRel> articlePolicyRelList = articlePolicyRelMapper.selectList(Wrappers.<ArticlePolicyRel>lambdaQuery().eq(ArticlePolicyRel::getArticleId, articleId));
        if (CollUtil.isEmpty(articlePolicyRelList)) {
            return null;
        }
        List<Long> policyIds = articlePolicyRelList.stream().map(ArticlePolicyRel::getPolicyId).collect(Collectors.toList());

        List<ArticlePolicy> articlePolicyList = articlePolicyMapper.selectList(Wrappers.<ArticlePolicy>lambdaQuery().in(ArticlePolicy::getArticleId, policyIds));

        // 最终处理结果Map
        TreeMap<Long, ArticlePolicy> policyResultMap = new TreeMap<>();

        List<ArticlePolicy> allPolicyList = articlePolicyMapper.getAllPolicy(new ArticlePolicy());
        // 所有政策Map
        Map<Long, ArticlePolicy> allPolicyMap = allPolicyList.stream().collect(Collectors.toMap(ArticlePolicy::getArticleId, x -> x));
        // 根据父级政策分组Map
        Map<String, List<ArticlePolicy>> parentPolicyMap = allPolicyList.stream().filter(item -> StrUtil.isNotBlank(item.getParentId())).collect(Collectors.groupingBy(ArticlePolicy::getParentId));

        // 查询每个政策的树结构(最多4层结构) 查找逻辑：上找3层，下找3层
        findPolicyParentRel(articlePolicyList, policyResultMap, allPolicyMap, parentPolicyMap);

        HashMap<Long, List<PolicyTreeVO>> allNodeMap = new HashMap<>();
        List<PolicyTreeVO> rootNode = getBaseTreeVos(policyResultMap, allNodeMap);
        if (CollUtil.isEmpty(rootNode)) {
            return Lists.newArrayList();
        }
        return TreeUtils.buildTree(rootNode, allNodeMap);
    }

    /**
     * 根据政策id查询所属政策树
     *
     * @param policyId
     * @return
     */
    @Override
    public List<PolicyTreeVO> getParentPolicy(Long policyId) {

        List<Long> policyIds = Arrays.asList(policyId);

        List<ArticlePolicy> articlePolicyList = articlePolicyMapper.selectList(Wrappers.<ArticlePolicy>lambdaQuery().in(ArticlePolicy::getArticleId, policyIds));

        List<ArticlePolicy> allPolicyList = articlePolicyMapper.getAllPolicy(new ArticlePolicy());
        // 所有政策Map
        Map<Long, ArticlePolicy> allPolicyMap = allPolicyList.stream().collect(Collectors.toMap(ArticlePolicy::getArticleId, x -> x));
        // 根据父级政策分组Map
        Map<String, List<ArticlePolicy>> parentPolicyMap = allPolicyList.stream().filter(item -> StrUtil.isNotBlank(item.getParentId())).collect(Collectors.groupingBy(ArticlePolicy::getParentId));

        // 最终处理结果Map
        TreeMap<Long, ArticlePolicy> policyResultMap = new TreeMap<>();
        // 查询每个政策的树结构(最多4层结构) 查找逻辑：上找3层，下找3层
        findPolicyParentRel(articlePolicyList, policyResultMap, allPolicyMap, parentPolicyMap);

        HashMap<Long, List<PolicyTreeVO>> allNodeMap = new HashMap<>();
        List<PolicyTreeVO> rootNode = getBaseTreeVos(policyResultMap, allNodeMap);
        if (CollUtil.isEmpty(rootNode)) {
            return Lists.newArrayList();
        }
        return TreeUtils.buildTree(rootNode, allNodeMap);
    }

    /**
     * 根据政策id查询关联政策树
     *
     * @param policyId
     * @return
     */
    @Override
    public List<BaseTreeVo> findPolicyRel(Long policyId) {


        ArticlePolicy articlePolicy = articlePolicyMapper.selectById(policyId);

        return findPolicyRel(articlePolicy);
    }

    /**
     * 根据政策id查询管理政策树
     *
     * @param policyId
     * @return
     */
    @Override
    public List<BaseTreeVo> findPolicyManageRel(Long policyId) {

        List<Long> policyIds = Arrays.asList(policyId);

        List<ArticlePolicy> articlePolicyList = articlePolicyMapper.selectList(Wrappers.<ArticlePolicy>lambdaQuery().in(ArticlePolicy::getArticleId, policyIds));

        // 最终处理结果Map
        TreeMap<Long, ArticlePolicy> policyResultMap = new TreeMap<>();
        findPolicyManageRel(articlePolicyList, policyResultMap);

        HashMap<Long, List<BaseTreeVo>> allNodeMap = new HashMap<>();
        List<BaseTreeVo> rootNode = getManageTreeVos(policyResultMap, allNodeMap);
        if (CollUtil.isEmpty(rootNode)) {
            return Lists.newArrayList();
        }
        return TreeUtils.buildTree(rootNode, allNodeMap);
    }

    public void getParentPolicyType(Map<Long, ArticlePolicy> allPolicyMap, ArticlePolicy policy, List<String> itemTypes) {

        ArticlePolicy articlePolicy = null;
        if (StrUtil.isNotBlank(policy.getManageRel())) {
            articlePolicy = allPolicyMap.get(Long.parseLong(policy.getManageRel()));
        } else {
            articlePolicy = allPolicyMap.get(Long.parseLong(policy.getParentId()));
        }
        if (Arrays.asList("1", "2", "3", "4").contains(articlePolicy.getItemType())) {
            if (articlePolicy.getItemType().equals("1")) {
                itemTypes.add("专项资金");
            } else if (articlePolicy.getItemType().equals("2")) {
                itemTypes.add("荣誉资质");
            } else if (articlePolicy.getItemType().equals("3")) {
                itemTypes.add("赛事活动");
            } else if (articlePolicy.getItemType().equals("4")) {
                itemTypes.add("其他");
            }
        } else {
            if (StrUtil.isNotBlank(articlePolicy.getManageRel())) {
                getParentPolicyType(allPolicyMap, articlePolicy, itemTypes);
            }
        }
    }

    private List<PolicyTreeVO> getNormalTreeVos(TreeMap<Long, ArticlePolicy> policyResultMap, HashMap<Long, List<PolicyTreeVO>> allNodeMap) {
        List<ArticlePolicy> sortArticlePolicy = policyResultMap.values().stream().sorted(Comparator.comparing(ArticlePolicy::getSort1).thenComparing(ArticlePolicy::getSort2).thenComparing(ArticlePolicy::getSort3)).collect(Collectors.toList());
        List<PolicyTreeVO> tsPolicy = Lists.newArrayList();
        PolicyTreeVO zx = new PolicyTreeVO();
        zx.setId("1000001");
        zx.setValue(1000001L);
        zx.setLabel("专项资金");
        tsPolicy.add(zx);
        PolicyTreeVO ry = new PolicyTreeVO();
        ry.setId("1000002");
        ry.setValue(1000002L);
        ry.setLabel("荣誉资质");
        tsPolicy.add(ry);
        PolicyTreeVO ss = new PolicyTreeVO();
        ss.setId("1000003");
        ss.setValue(1000003L);
        ss.setLabel("赛事活动");
        tsPolicy.add(ss);
        PolicyTreeVO qt = new PolicyTreeVO();
        qt.setId("1000004");
        qt.setValue(1000004L);
        qt.setLabel("其他");
        tsPolicy.add(qt);
        allNodeMap.put(0L, tsPolicy);
        for (ArticlePolicy item : sortArticlePolicy) {
            if (StrUtil.isNotBlank(item.getParentId())) {
                if (item.getParentId().contains(",")) {
                    continue;
                }
            }

            Long parentId = StrUtil.isBlank(item.getParentId()) ? 0 : Long.parseLong(item.getParentId());
            if (("6".equals(item.getItemType()) || "7".equals(item.getItemType())) && StrUtil.isNotBlank(item.getManageRel())) {
                continue;
            }
            List<PolicyTreeVO> nodeList = allNodeMap.get(parentId);
            if (CollectionUtils.isEmpty(nodeList)) {

                nodeList = Lists.newArrayList();
            }
            PolicyTreeVO policyTreeVO = new PolicyTreeVO();
            policyTreeVO.setId(String.valueOf(item.getArticleId()));
            policyTreeVO.setValue(item.getArticleId());
            policyTreeVO.setLabel(item.getName());
//            policyTreeVO.setItemType(StrUtil.isNotBlank(item.getItemType()) ? item.getItemType() : "99");

            boolean flag = false;
            if (parentId == 0) {
                Long tsParentId = parentId;
                if ("1".equals(item.getItemType())) {
                    tsParentId = 1000001L;
                } else if ("2".equals(item.getItemType())) {
                    tsParentId = 1000002L;
                } else if ("3".equals(item.getItemType())) {
                    tsParentId = 1000003L;
                } else if ("4".equals(item.getItemType())) {
                    tsParentId = 1000004L;
                }

                if (tsParentId != 0L) {
                    List<PolicyTreeVO> tsNodeList = allNodeMap.get(tsParentId);
                    if (CollectionUtils.isEmpty(tsNodeList)) {

                        tsNodeList = Lists.newArrayList();
                    }
                    tsNodeList.add(policyTreeVO);
                    allNodeMap.put(tsParentId, tsNodeList);
                    flag = true;
                }
            }
            if (!flag) {
                nodeList.add(policyTreeVO);
                allNodeMap.put(parentId, nodeList);
            }
        }
        List<PolicyTreeVO> rootNode = allNodeMap.get(0L);
        return rootNode;
    }

    private List<PolicyTreeVO> getBaseTreeVos(TreeMap<Long, ArticlePolicy> policyResultMap, HashMap<Long, List<PolicyTreeVO>> allNodeMap) {
        List<ArticlePolicy> sortArticlePolicy = policyResultMap.values().stream().sorted(Comparator.comparing(ArticlePolicy::getSort1).thenComparing(ArticlePolicy::getSort2).thenComparing(ArticlePolicy::getSort3)).collect(Collectors.toList());
        for (ArticlePolicy item : sortArticlePolicy) {
            if (StrUtil.isNotBlank(item.getParentId())) {
                if (item.getParentId().contains(",")) {
                    continue;
                }
            }
            Long parentId = StrUtil.isBlank(item.getParentId()) ? 0 : Long.parseLong(item.getParentId());
            List<PolicyTreeVO> nodeList = allNodeMap.get(parentId);
            if (CollectionUtils.isEmpty(nodeList)) {

                nodeList = Lists.newArrayList();
            }
            PolicyTreeVO policyTreeVO = new PolicyTreeVO();
            policyTreeVO.setId(String.valueOf(item.getArticleId()));
            policyTreeVO.setValue(item.getArticleId());
            policyTreeVO.setLabel(item.getName());
            policyTreeVO.setItemType(StrUtil.isNotBlank(item.getItemType()) ? item.getItemType() : "99");
            nodeList.add(policyTreeVO);
            allNodeMap.put(parentId, nodeList);
        }
        List<PolicyTreeVO> rootNode = allNodeMap.get(0L);
        return rootNode;
    }

    private List<BaseTreeVo> getManageTreeVos(TreeMap<Long, ArticlePolicy> policyResultMap, HashMap<Long, List<BaseTreeVo>> allNodeMap) {
        List<ArticlePolicy> sortArticlePolicy = policyResultMap.values().stream().sorted(Comparator.comparing(ArticlePolicy::getSort1).thenComparing(ArticlePolicy::getSort2).thenComparing(ArticlePolicy::getSort3)).collect(Collectors.toList());
        for (ArticlePolicy item : sortArticlePolicy) {

            Long manegeId = StrUtil.isBlank(item.getManageRel()) ? 0 : Long.parseLong(item.getManageRel());
            List<BaseTreeVo> nodeList = allNodeMap.get(manegeId);
            if (CollectionUtils.isEmpty(nodeList)) {

                nodeList = Lists.newArrayList();
            }
            BaseTreeVo policyTreeVO = new BaseTreeVo();
            policyTreeVO.setId(String.valueOf(item.getArticleId()));
            policyTreeVO.setValue(item.getArticleId());
            policyTreeVO.setLabel(item.getName());
            nodeList.add(policyTreeVO);
            allNodeMap.put(manegeId, nodeList);
        }
        List<BaseTreeVo> rootNode = allNodeMap.get(0L);
        return rootNode;
    }

    // 查询所属关系政策树
    private void findPolicyParentRel(Collection<ArticlePolicy> articlePolicyList, TreeMap<Long, ArticlePolicy> policyResultMap, Map<Long, ArticlePolicy> allPolicyMap, Map<String, List<ArticlePolicy>> parentPolicyMap) {

        for (ArticlePolicy articlePolicy : articlePolicyList) {

            policyResultMap.put(articlePolicy.getArticleId(), articlePolicy);

            if (StrUtil.isNotBlank(articlePolicy.getParentId())) {
                ArticlePolicy parent1 = allPolicyMap.get(Long.parseLong(articlePolicy.getParentId()));
                if (Objects.nonNull(parent1)) {
                    policyResultMap.put(parent1.getArticleId(), parent1);
                    if (StrUtil.isNotBlank(parent1.getParentId())) {
                        ArticlePolicy parent2 = allPolicyMap.get(Long.parseLong(parent1.getParentId()));
                        if (Objects.nonNull(parent2)) {
                            policyResultMap.put(parent2.getArticleId(), parent2);
                            if (StrUtil.isNotBlank(parent2.getParentId())) {
                                ArticlePolicy parent3 = allPolicyMap.get(Long.parseLong(parent2.getParentId()));
                                if (Objects.nonNull(parent3)) {
                                    policyResultMap.put(parent3.getArticleId(), parent3);
                                    if (StrUtil.isNotBlank(parent3.getParentId())) {
                                        ArticlePolicy parent4 = allPolicyMap.get(Long.parseLong(parent3.getParentId()));
                                        if (Objects.nonNull(parent4)) {
                                            policyResultMap.put(parent4.getArticleId(), parent4);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            List<ArticlePolicy> childrenList1 = parentPolicyMap.get(String.valueOf(articlePolicy.getArticleId()));
            if (CollUtil.isNotEmpty(childrenList1)) {
                for (ArticlePolicy children1 : childrenList1) {
                    policyResultMap.put(children1.getArticleId(), children1);
                    List<ArticlePolicy> childrenList2 = parentPolicyMap.get(String.valueOf(children1.getArticleId()));
                    if (CollUtil.isNotEmpty(childrenList2)) {
                        for (ArticlePolicy children2 : childrenList2) {
                            policyResultMap.put(children2.getArticleId(), children2);
                            List<ArticlePolicy> childrenList3 = parentPolicyMap.get(String.valueOf(children2.getArticleId()));
                            if (CollUtil.isNotEmpty(childrenList3)) {
                                for (ArticlePolicy children3 : childrenList3) {
                                    if (Objects.nonNull(children3)) {
                                        policyResultMap.put(children3.getArticleId(), children3);
                                        List<ArticlePolicy> childrenList4 = parentPolicyMap.get(String.valueOf(children3.getArticleId()));
                                        if (CollUtil.isNotEmpty(childrenList4)) {
                                            for (ArticlePolicy children4 : childrenList4) {
                                                if (Objects.nonNull(children4)) {
                                                    policyResultMap.put(children4.getArticleId(), children4);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

        }
    }

    // 查询关联关系政策树
    private List<BaseTreeVo> findPolicyRel(ArticlePolicy articlePolicy) {

        List<ArticlePolicy> allPolicyList = articlePolicyMapper.getAllPolicy(new ArticlePolicy());

        // 所有政策Map
        Map<Long, ArticlePolicy> allPolicyMap = allPolicyList.stream().collect(Collectors.toMap(ArticlePolicy::getArticleId, x -> x));
        List<BaseTreeVo> result = Lists.newArrayList();
        BaseTreeVo policyTreeVO = new BaseTreeVo();
        policyTreeVO.setId(String.valueOf(articlePolicy.getArticleId()));
        policyTreeVO.setValue(articlePolicy.getArticleId());
        policyTreeVO.setLabel(articlePolicy.getName());

        List<BaseTreeVo> childrenResult = Lists.newArrayList();
        if (StrUtil.isNotBlank(articlePolicy.getConnection())) {
            String[] connectionIds = articlePolicy.getConnection().split(",");
            for (String connectionId : connectionIds) {
                if (StrUtil.isNotBlank(connectionId)) {
                    ArticlePolicy childrenPolicy = allPolicyMap.get(Long.parseLong(connectionId));
                    if (Objects.nonNull(childrenPolicy)) {
                        BaseTreeVo childrenPolicyTreeVO = new BaseTreeVo();
                        childrenPolicyTreeVO.setId(String.valueOf(childrenPolicy.getArticleId()));
                        childrenPolicyTreeVO.setValue(childrenPolicy.getArticleId());
                        childrenPolicyTreeVO.setLabel(childrenPolicy.getName());
                        childrenResult.add(childrenPolicyTreeVO);
                    }
                }
            }
            policyTreeVO.setChildren(childrenResult);
        }
        result.add(policyTreeVO);
        return result;
    }

    // 查询管理关系政策树
    private void findPolicyManageRel(List<ArticlePolicy> articlePolicyList, TreeMap<Long, ArticlePolicy> policyResultMap) {

        List<ArticlePolicy> allPolicyList = articlePolicyMapper.getAllPolicy(new ArticlePolicy());
        // 所有政策Map
        Map<Long, ArticlePolicy> allPolicyMap = allPolicyList.stream().collect(Collectors.toMap(ArticlePolicy::getArticleId, x -> x));

        Map<String, ArticlePolicy> topArticlePolicyMap = new HashMap<>();
        for (ArticlePolicy articlePolicy : articlePolicyList) {
            getManageTopRel(articlePolicy, allPolicyMap, topArticlePolicyMap);
        }

        // 筛选出有管理关系的所有政策
        List<ArticlePolicy> managePolicyList = allPolicyList.stream().filter(item -> StrUtil.isNotBlank(item.getManageRel())).collect(Collectors.toList());
        Map<Long, List<ArticlePolicy>> managePolicyMap = new HashMap<>();
        for (ArticlePolicy item : managePolicyList) {
            String manageId = item.getManageRel();
            List<ArticlePolicy> articlePolicyTempList = managePolicyMap.get(Long.parseLong(manageId));
            if (CollUtil.isEmpty(articlePolicyTempList)) {
                articlePolicyTempList = Lists.newArrayList();
            }
            articlePolicyTempList.add(item);
            managePolicyMap.put(Long.parseLong(manageId), articlePolicyTempList);
        }

        ArticlePolicy topArticlePolicy = topArticlePolicyMap.get("top");
        policyResultMap.put(topArticlePolicy.getArticleId(), topArticlePolicy);
        getManageChildRel(topArticlePolicy.getArticleId(), managePolicyMap, policyResultMap);
    }

    private void getManageTopRel(ArticlePolicy articlePolicy, Map<Long, ArticlePolicy> allPolicyMap, Map<String, ArticlePolicy> topArticlePolicy) {
        if (StrUtil.isBlank(articlePolicy.getManageRel())) {
            topArticlePolicy.put("top", articlePolicy);
        } else {
            ArticlePolicy articlePolicyTemp = allPolicyMap.get(Long.parseLong(articlePolicy.getManageRel()));
            getManageTopRel(articlePolicyTemp, allPolicyMap, topArticlePolicy);
        }
    }

    private void getManageChildRel(Long manageId, Map<Long, List<ArticlePolicy>> ManagePolicyMap, TreeMap<Long, ArticlePolicy> policyResultMap) {
        if (ManagePolicyMap.containsKey(manageId)) {
            List<ArticlePolicy> articlePolicyList = ManagePolicyMap.get(manageId);
            for (ArticlePolicy articlePolicy : articlePolicyList) {
                policyResultMap.put(articlePolicy.getArticleId(), articlePolicy);
                getManageChildRel(articlePolicy.getArticleId(), ManagePolicyMap, policyResultMap);
            }
        }
    }

    // 查询演变关系政策树
    @Override
    public List<List<EvolutionVO>> findPolicyEvolutionRel(Long articleId) {

        List<ArticlePolicy> allPolicyList = articlePolicyMapper.getAllPolicy(new ArticlePolicy());
        // 所有政策Map
        Map<Long, ArticlePolicy> allPolicyMap = allPolicyList.stream().collect(Collectors.toMap(ArticlePolicy::getArticleId, x -> x));
        List<List<EvolutionVO>> result = Lists.newArrayList();
        ArticlePolicy articlePolicy = allPolicyMap.get(articleId);
        // 添加所有父级演变的政策
        getParentEvolutionRel(articlePolicy, allPolicyMap, result);

        // 添加本身
        List<EvolutionVO> evolutionVOList = Lists.newArrayList();
        EvolutionVO evolutionVO = new EvolutionVO();
        evolutionVO.setArticleId(articlePolicy.getArticleId());
        evolutionVO.setName(articlePolicy.getName());
        evolutionVOList.add(evolutionVO);
        result.add(evolutionVOList);

        // 筛选出有演变关系的所有政策
        List<ArticlePolicy> evolutionPolicyList = allPolicyList.stream().filter(item -> StrUtil.isNotBlank(item.getEvolutionRel())).collect(Collectors.toList());
        Map<Long, List<ArticlePolicy>> evolutionPolicyMap = new HashMap<>();
        for (ArticlePolicy item : evolutionPolicyList) {
            String[] evolutioIds = item.getEvolutionRel().split(",");
            for (String evolutioId : evolutioIds) {
                List<ArticlePolicy> articlePolicyTempList = evolutionPolicyMap.get(Long.parseLong(evolutioId));
                if (CollUtil.isEmpty(articlePolicyTempList)) {
                    articlePolicyTempList = Lists.newArrayList();
                }
                articlePolicyTempList.add(item);
                evolutionPolicyMap.put(Long.parseLong(evolutioId), articlePolicyTempList);
            }
        }
        // 添加所有子级演变的政策
        getChildEvolutionRel(articlePolicy.getArticleId(), evolutionPolicyMap, result);
        return result;
    }

    private void getParentEvolutionRel(ArticlePolicy articlePolicy, Map<Long, ArticlePolicy> allPolicyMap, List<List<EvolutionVO>> result) {
        if (StrUtil.isNotBlank(articlePolicy.getEvolutionRel())) {
            String[] evolutioIds = articlePolicy.getEvolutionRel().split(",");
            List<EvolutionVO> evolutionVOList = Lists.newArrayList();
            for (String evolutioId : evolutioIds) {
                EvolutionVO evolutionVO = new EvolutionVO();
                ArticlePolicy articlePolicyEvolution = allPolicyMap.get(Long.parseLong(evolutioId));
                evolutionVO.setArticleId(articlePolicyEvolution.getArticleId());
                evolutionVO.setName(articlePolicyEvolution.getName());
                evolutionVOList.add(evolutionVO);
                getParentEvolutionRel(articlePolicyEvolution, allPolicyMap, result);
            }
            result.add(evolutionVOList);
        }
    }

    private void getChildEvolutionRel(Long evolutioId, Map<Long, List<ArticlePolicy>> evolutionPolicyMap, List<List<EvolutionVO>> result) {
        if (evolutionPolicyMap.containsKey(evolutioId)) {
            List<ArticlePolicy> articlePolicyList = evolutionPolicyMap.get(evolutioId);
            List<EvolutionVO> evolutionVOList = Lists.newArrayList();
            for (ArticlePolicy articlePolicy : articlePolicyList) {
                EvolutionVO evolutionVO = new EvolutionVO();
                evolutionVO.setArticleId(articlePolicy.getArticleId());
                evolutionVO.setName(articlePolicy.getName());
                evolutionVOList.add(evolutionVO);
                getChildEvolutionRel(articlePolicy.getArticleId(), evolutionPolicyMap, result);
            }
            result.add(evolutionVOList);
        }
    }

    private void parkAreaHandler(NormalPolicyBO bo) {
        if (CollUtil.isNotEmpty(bo.getAreaIds())) {
            List<Long> lastPark = Lists.newArrayList();
            if (bo.getAreaIds().size() > 0) {
                Long park1 = Long.parseLong(bo.getAreaIds().get(0));
                bo.setPark1(park1);
                lastPark.add(bo.getPark1());
            }
            if (bo.getAreaIds().size() > 1) {
                Long park2 = Long.parseLong(bo.getAreaIds().get(1));
                bo.setPark2(park2);
                lastPark.add(bo.getPark2());
            }
            if (bo.getAreaIds().size() > 2) {
                Long park3 = Long.parseLong(bo.getAreaIds().get(2));
                bo.setPark3(park3);
                lastPark.add(bo.getPark3());
            }
            if (bo.getAreaIds().size() > 3) {
                Long park4 = Long.parseLong(bo.getAreaIds().get(3));
                bo.setPark4(park4);
                lastPark.add(bo.getPark4());
            }
            if (bo.getAreaIds().size() > 4) {
                Long park5 = Long.parseLong(bo.getAreaIds().get(4));
                bo.setPark5(park5);
                lastPark.add(bo.getPark5());
            }
            if (bo.getAreaIds().size() > 5) {
                Long park6 = Long.parseLong(bo.getAreaIds().get(5));
                bo.setPark6(park6);
                lastPark.add(bo.getPark6());
            }
            bo.setLastPark(lastPark);
        }
    }

    @Override
    public NormalPolicyVO normalPolicy(NormalPolicyBO bo) {
        NormalPolicyVO normalPolicyVO = new NormalPolicyVO();
        List<ExcelDetail> excelDetailList = Lists.newArrayList();
        SysUser user = getLoginUser().getUser();

        // 所有主管部门
        List<OrgInfo> orgList = orgInfoMapper.selectList(Wrappers.<OrgInfo>lambdaQuery().select(OrgInfo::getOrgId, OrgInfo::getType, OrgInfo::getOrgName, OrgInfo::getParentOrgId).eq(OrgInfo::getIsDeleted, "0"));
        Map<Long, OrgInfo> orgMap = orgList.stream().collect(Collectors.toMap(OrgInfo::getOrgId, x -> x));

        // 主管类型数据
        List<SysDictData> sysDictDataList = dictTypeService.selectDictDataByType("org_type");
        Map<String, Long> orgTypeMap = sysDictDataList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictSort));

        List<ArticlePolicy> policyList = articlePolicyMapper.getAllPolicy(new ArticlePolicy());
        // 所有政策Map
        Map<Long, ArticlePolicy> allPolicyMap = policyList.stream().filter(item -> "1".equals(item.getStatus())).collect(Collectors.toMap(ArticlePolicy::getArticleId, x -> x));
        // 所有父级政策
        Map<String, List<ArticlePolicy>> allParentPolicy = policyList.stream().filter(item -> StrUtil.isNotBlank(item.getParentId())).collect(Collectors.groupingBy(ArticlePolicy::getParentId));

        // 前置政策Map
        Map<Long, ArticlePolicy> prePolicyMap = new HashMap();
        // 前置父级政策集合
        List<String> preParentPolicyList = Lists.newArrayList();

        // 判断用户是否是管理员，不是则鉴权
        if (!SysUser.isAdmin(user.getUserId())) {
            WebAuthVo webAuthVo = webRoleAuthService.getAuthContent();
            int pc = Integer.parseInt(webAuthVo.getPc());
            String createTime = DateUtil.formatDate(DateUtil.offsetDay(new Date(), -90));
            int count = userPlanMapper.getPlanCount(createTime, user.getUserId());
            if (pc - count <= 0) {
                throw new ServiceException("当前规划次数本季度内已达上线，开通更高级别会员可获得更多权益");
            }
        }

        // 系统无数据，调用企查查数据
        Company company = null;
        if (bo.getCompanyId() == 0L) {
            company = companyService.getQccCompany(bo.getCompanyName());
        } else {
            company = companyMapper.selectById(bo.getCompanyId());
            if (Objects.nonNull(company)) {
                if (company.getGetApi() != 1L) {
                    company = companyService.getQccCompany(company.getName());
                }
            }
        }
        if (StrUtil.isNotBlank(company.getParkAreaId())) {
            List<ParkArea> parkAreaList = parkAreaMapper.selectList(Wrappers.<ParkArea>lambdaQuery());
            Map<Long, String> parkAreaMap = parkAreaList.stream().collect(Collectors.toMap(ParkArea::getId, ParkArea::getName));
            List<String> parkAreaIdList = Arrays.asList(company.getParkAreaId().split(","));
            List<String> parkAreaNameList = new ArrayList<>();
            for (String parkAreaId : parkAreaIdList) {
                if (!"null".equals(parkAreaId)) {
                    parkAreaNameList.add(parkAreaMap.get(Long.parseLong(parkAreaId)));
                }
            }
            company.setParkAreaName(String.join("-", parkAreaNameList));
        }
        normalPolicyVO.setCompany(company);

        List<String> companyNameList = Lists.newArrayList();
        companyNameList.add(company.getName());
        // 根据单位名称（含：曾用名），在平台“项目立项数据库”中查询，查询该单位已立项项目信息
        if (StrUtil.isNotBlank(company.getHistoryName())) {
            String[] companyNames = company.getHistoryName().split(";");
            for (String companyName : companyNames) {
                if (StrUtil.isNotBlank(companyName) && !"无".equals(companyName)) {
                    if (companyName.contains("（")) {
                        companyName = companyName.substring(0, companyName.indexOf("（"));
                        companyNameList.add(companyName);
                    }
                }
            }
        }
        bo.setCompanyNameList(companyNameList);
        company.setCompanyNameList(companyNameList);

        ServiceException.throwExOnCondition(Objects.isNull(company), "未查询到对应企业数据");

        // 地区范围处理
        if (StrUtil.isNotBlank(company.getParkAreaId())) {
            bo.setAreaIds(Arrays.asList(company.getParkAreaId().split(",")));
        }
        parkAreaHandler(bo);

        if (Objects.nonNull(company.getIndustry4())) {
            bo.setIndustryId("," + company.getIndustry4());
        }

        // 标签处理
        List<Tag> tagList = tagMapper.selectList(Wrappers.lambdaQuery());
        Map<String, Long> tagNamesMap = tagList.stream().collect(Collectors.toMap(Tag::getName, Tag::getId));
        screenHandler(tagNamesMap, company, bo);

        // 根据“单位类别标签”、“成立时间标签”、“所属地区”（项目类别覆盖范围）、“所属园区”（项目类别覆盖范围）、“所属行业标签”、“收入规模标签”、“人员规模标签”与“项目状态标签” 查询政策数据
        // 根据“单位类别标签”、“成立时间标签”、“所属地区”（项目类别覆盖范围）、“所属园区”（项目类别覆盖范围）、“所属行业标签”、“收入规模标签”、“人员规模标签”与“项目状态标签”为“现行有效”的项目类别进行匹配
        List<ArticlePolicy> articlePolicyList = articlePolicyMapper.normalPolicy(bo);
        // 排重List
        List<Long> articleIds = Lists.newArrayList();
        if (CollUtil.isNotEmpty(articlePolicyList)) {
            articleIds = articlePolicyList.stream().map(ArticlePolicy::getArticleId).collect(Collectors.toList());
        }

        Set<ArticlePolicy> allPolicyList = new HashSet<>();
        Map<String, ItemStatisticsVO> normalStatisticsMap = new HashMap<>();
        Map<String, ItemStatisticsVO> childNormalStatisticsMap = new HashMap<>();
        for (ArticlePolicy articlePolicy : articlePolicyList) {

            if (!Arrays.asList("1", "2", "3", "4").contains(articlePolicy.getItemType())) {
                // 地方管理、地方切块切换至最高级
                manageHandler(company, tagNamesMap, articlePolicy, allPolicyList, allPolicyMap, allParentPolicy, prePolicyMap, preParentPolicyList);
            } else {
                // 有效期期限判断
                expiresVerify(company, tagNamesMap, allPolicyList, articlePolicy, allPolicyMap, allParentPolicy, prePolicyMap, preParentPolicyList);
            }
        }

        // 匹配查询已立项政策数据
        List<ArticlePolicy> approvalPolicyList = articlePolicyMapper.getApprovalPolicy(bo);

        Map<String, ItemStatisticsVO> itemStatisticsMap = new HashMap<>();
        Map<String, ItemStatisticsVO> childItemStatisticsMap = new HashMap<>();
        for (ArticlePolicy articlePolicy : approvalPolicyList) {
            if (!Arrays.asList("1", "2", "3", "4").contains(articlePolicy.getItemType())) {
                // 地方管理、地方切块切换至最高级
                manageHandler(company, tagNamesMap, articlePolicy, allPolicyList, allPolicyMap, allParentPolicy, prePolicyMap, preParentPolicyList);
            } else if ("1".equals(articlePolicy.getItemType())) {
                // 有效期期限判断
                expiresVerify(company, tagNamesMap, allPolicyList, articlePolicy, allPolicyMap, allParentPolicy, prePolicyMap, preParentPolicyList);
            }

            // 立项政策(荣誉资质、赛事活动、其他)关联的政策(专项资金)钠入规划（获得时间为1年内）
            else if ("2".equals(articlePolicy.getItemType()) || "3".equals(articlePolicy.getItemType()) || "4".equals(articlePolicy.getItemType())) {
                if (StrUtil.isNotBlank(articlePolicy.getConnection())) {
                    String[] connectionIds = articlePolicy.getConnection().split(",");
                    bo.setConnectionIds(Arrays.asList(connectionIds));
                    if (connectionIds.length > 0) {
                        // 查询关联政策（已立项政策数据 的 关联政策数据  eg:a 政策 关联 b、c政策 ，查出 b、c 政策(有效立项数据) 返回 ）
                        List<ArticlePolicy> connectionPolicyList = articlePolicyMapper.getConnectionPolicy(bo);
                        for (ArticlePolicy policy : connectionPolicyList) {
                            if (!articleIds.contains(policy.getArticleId())) {
                                SelectItemByPolicyBO query = new SelectItemByPolicyBO();
                                query.setPolicyId(String.valueOf(policy.getArticleId()));
                                query.setCompanyNameList(company.getCompanyNameList());
                                ExcelDetail excelDetail = excelDetailMapper.selectItemByPolicyAndCompany(query);
                                if (Objects.nonNull(excelDetail)) {
                                    long betweenDay = DateUtil.betweenDay(excelDetail.getApprovalTime(), DateUtil.date(), true);
                                    if (betweenDay <= 365) {
                                        expiresVerify(company, tagNamesMap, allPolicyList, policy, allPolicyMap, allParentPolicy, prePolicyMap, preParentPolicyList);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        // 最终处理结果Map
        TreeMap<Long, ArticlePolicy> policyResultMap = new TreeMap<>();

        // 将前置政策加入规划
        for (Map.Entry<Long, ArticlePolicy> item : prePolicyMap.entrySet()) {
            allPolicyList.add(item.getValue());
        }

        List<ItemDataVO> policyDataList = Lists.newArrayList();
        int sortNo = 1;
        // 匹配结果数据统计
        Map<Long, String> policyListMap = new HashMap<>();
        for (ArticlePolicy articlePolicy : allPolicyList) {

            if (!allParentPolicy.containsKey(String.valueOf(articlePolicy.getArticleId()))) {

                if (policyListMap.containsKey(articlePolicy.getArticleId())) {
                    continue;
                }
                // 匹配结果数据统计
                statisticsMapHandler(normalStatisticsMap, childNormalStatisticsMap, articlePolicy, allParentPolicy);
                policyListMap.put(articlePolicy.getArticleId(), "1");
                ItemDataVO itemDataVO = new ItemDataVO();
                itemDataVO.setBenefits(articlePolicy.getBenefits());
                itemDataVO.setStatus(2);

                itemDataVO.setStatusName("未申报");
                if (Objects.nonNull(articlePolicy.getCutOffTime())) {
                    Date cutOffTime = articlePolicy.getCutOffTime();
//                    Date cutOffTime = DateUtil.offsetHour(articlePolicy.getCutOffTime(),17);
//                    articlePolicy.setCutOffTime(DateUtil.offsetDay(cutOffTime, 1));
                    if (DateUtil.beginOfYear(new Date()).compareTo(cutOffTime) > 0) {
                        itemDataVO.setRemainingDay(DateUtil.formatDate(cutOffTime));
                        itemDataVO.setStatusName("未申报");
                    } else if (cutOffTime.compareTo(new Date()) < 0) {
                        itemDataVO.setRemainingDay(DateUtil.formatDate(cutOffTime));
                        itemDataVO.setStatus(3);
                        itemDataVO.setStatusName("已截止");
                    } else {
                        itemDataVO.setRemainingDay(String.valueOf(DateUtil.betweenDay(new Date(), cutOffTime, true)));
                        itemDataVO.setStatus(1);
                        itemDataVO.setStatusName("申报中");
                    }
                }
                itemDataVO.setCutOffTime(DateUtil.formatDate(articlePolicy.getCutOffTime()));
                itemDataVO.setType(Integer.parseInt(articlePolicy.getItemType()));
                if (itemDataVO.getType() == 1) {
                    itemDataVO.setTypeName("专项资金");
                } else if (itemDataVO.getType() == 2) {
                    itemDataVO.setTypeName("荣誉资质");
                } else if (itemDataVO.getType() == 3) {
                    itemDataVO.setTypeName("赛事活动");
                } else if (itemDataVO.getType() == 4) {
                    itemDataVO.setTypeName("其他");
                } else {
                    List<String> itemTypes = Lists.newArrayList();
                    getParentPolicyType(allPolicyMap, articlePolicy, itemTypes);
                    itemDataVO.setTypeName(itemTypes.get(0));
                    if ("专项资金".equals(itemDataVO.getTypeName())) {
                        itemDataVO.setType(1);
                    } else if ("荣誉资质".equals(itemDataVO.getTypeName())) {
                        itemDataVO.setType(2);
                    } else if ("赛事活动".equals(itemDataVO.getTypeName())) {
                        itemDataVO.setType(3);
                    } else if ("其他".equals(itemDataVO.getTypeName())) {
                        itemDataVO.setType(4);
                    }
                }
                if (StrUtil.isNotBlank(articlePolicy.getItemLevel())) {
                    itemDataVO.setItemLevel(Integer.parseInt(articlePolicy.getItemLevel()));
                }
                int orgSort = 0;
                if (Objects.nonNull(articlePolicy.getOrgId())) {
                    OrgInfo orgInfo = orgMap.get(articlePolicy.getOrgId());
                    if (Objects.nonNull(orgInfo)) {
                        String orgName3 = orgInfo.getOrgName();
                        String orgName2 = "";
                        String orgName1 = "";
                        List<String> orgNames = Lists.newArrayList();
                        List<ItemDataVO.ItemOrgDetail> orgDetailList = Lists.newArrayList();
                        if (Objects.nonNull(orgInfo.getParentOrgId()) && orgInfo.getParentOrgId() != 0L) {
                            OrgInfo orgInfo2 = orgMap.get(orgInfo.getParentOrgId());
                            orgName2 = orgInfo2.getOrgName();
                            if (Objects.nonNull(orgInfo2.getParentOrgId()) && orgInfo2.getParentOrgId() != 0L) {
                                OrgInfo orgInfo1 = orgMap.get(orgInfo2.getParentOrgId());
                                orgName1 = orgInfo1.getOrgName();
                                ItemDataVO.ItemOrgDetail itemOrgDetail1 = new ItemDataVO.ItemOrgDetail();
                                itemOrgDetail1.setOrgId(orgInfo1.getOrgId());
                                itemOrgDetail1.setName(orgInfo1.getOrgName());
                                orgDetailList.add(itemOrgDetail1);
                                orgNames.add(orgName1);
                            }
                            orgNames.add(orgName2);
                            ItemDataVO.ItemOrgDetail itemOrgDetail2 = new ItemDataVO.ItemOrgDetail();
                            itemOrgDetail2.setOrgId(orgInfo2.getOrgId());
                            itemOrgDetail2.setName(orgInfo2.getOrgName());
                            orgDetailList.add(itemOrgDetail2);
                        }
                        orgNames.add(orgName3);
                        ItemDataVO.ItemOrgDetail itemOrgDetail3 = new ItemDataVO.ItemOrgDetail();
                        itemOrgDetail3.setOrgId(orgInfo.getOrgId());
                        itemOrgDetail3.setName(orgInfo.getOrgName());
                        orgDetailList.add(itemOrgDetail3);
                        itemDataVO.setOrgList(orgDetailList);
                        itemDataVO.setOrgName(String.join("-", orgNames));
                        Long orgSortLong = orgTypeMap.get(orgInfo.getType());
                        if (Objects.nonNull(orgSortLong)) {
                            orgSort = orgSortLong.intValue();
                        }
                    }
                }
                itemDataVO.setOrgSort(orgSort);
                List<ItemDataVO.ItemDataDetail> itemDataDetailList = Lists.newArrayList();
                policyIdHandler(itemDataDetailList, allPolicyMap, articlePolicy, allParentPolicy);
                itemDataDetailList = itemDataDetailList.stream().sorted(Comparator.comparing(ItemDataVO.ItemDataDetail::getItemGrade).thenComparing(ItemDataVO.ItemDataDetail::getPolicyId)).collect(Collectors.toList());
                itemDataVO.setPolicyList(itemDataDetailList);
                itemDataVO.setPolicyId(String.valueOf(articlePolicy.getArticleId()));
                itemDataVO.setSimplePolicyName(articlePolicy.getName());
                if (CollUtil.isNotEmpty(itemDataDetailList)) {
                    List<String> policyNames = itemDataDetailList.stream().sorted(Comparator.comparing(ItemDataVO.ItemDataDetail::getItemGrade)).map(ItemDataVO.ItemDataDetail::getTitle).collect(Collectors.toList());
                    itemDataVO.setPolicyName(String.join("-", policyNames));
                }
                policyDataList.add(itemDataVO);

            }
        }
        if (CollUtil.isNotEmpty(policyDataList)) {
            policyDataList = policyDataList.stream().sorted(Comparator.comparing(ItemDataVO::getStatus)
                    .thenComparing(ItemDataVO::getType).thenComparing(ItemDataVO::getItemLevel).thenComparing(ItemDataVO::getOrgSort)).collect(Collectors.toList());
            for (ItemDataVO itemDataVO : policyDataList) {
                itemDataVO.setSortNo(sortNo);
                sortNo++;
            }
        }
        normalPolicyVO.setPolicyList(policyDataList);
        // 立项结果统计
        List<ArticlePolicy> itemDataStatisticsList = excelDetailMapper.selectItemDataStatistics(companyNameList);
        List<ArticlePolicy> itemDataList = Lists.newArrayList();

        for (ArticlePolicy articlePolicy : itemDataStatisticsList) {
            int orgSort = 0;
            if (Objects.nonNull(articlePolicy.getOrgId())) {
                OrgInfo orgInfo = orgMap.get(articlePolicy.getOrgId());
                if (Objects.nonNull(orgInfo)) {
                    Long orgSortLong = orgTypeMap.get(orgInfo.getType());
                    if (Objects.nonNull(orgSortLong)) {
                        orgSort = orgSortLong.intValue();
                    }
                }
            }
            if(Objects.isNull(articlePolicy.getItemLevel())) {
                articlePolicy.setItemLevel("0");
            }
            if(Objects.isNull(articlePolicy.getYear())) {
                articlePolicy.setYear("0");
            }
            articlePolicy.setOrgSort(orgSort);
        }
        itemDataStatisticsList = itemDataStatisticsList.stream().sorted(Comparator.comparing(ArticlePolicy::getItemLevel).thenComparing(ArticlePolicy::getOrgSort)).collect(Collectors.toList());
        int itemSortNo = 1;
        for (ArticlePolicy articlePolicy : itemDataStatisticsList) {
            // 立项结果统计
            statisticsMapHandler(itemStatisticsMap, childItemStatisticsMap, articlePolicy, allParentPolicy);
            if (!allParentPolicy.containsKey(String.valueOf(articlePolicy.getArticleId()))) {
                articlePolicy.setSortNo(itemSortNo);
                itemDataList.add(articlePolicy);
                itemSortNo++;
            }
        }
        normalPolicyVO.setItemList(itemDataList);
        // 查询每个政策的树结构(最多5层结构) 查找逻辑：上找4层，下找4层
        findPolicyParentRel(allPolicyList, policyResultMap, allPolicyMap, allParentPolicy);

        HashMap<Long, List<PolicyTreeVO>> allNodeMap = new HashMap<>();
        List<PolicyTreeVO> rootNode = getNormalTreeVos(policyResultMap, allNodeMap);
        if (CollUtil.isEmpty(rootNode)) {
            return normalPolicyVO;
        }

        List<PolicyTreeVO> result = TreeUtils.buildTree(rootNode, allNodeMap);
//        result = result.stream().sorted(Comparator.comparing(PolicyTreeVO::getItemType)).collect(Collectors.toList());

        normalPolicyVO.setPolicyTreeList(result);
        statisticsMapConver(normalStatisticsMap, childNormalStatisticsMap);
        statisticsMapConver(itemStatisticsMap, childItemStatisticsMap);
        if (itemStatisticsMap.containsKey("1")) {
            normalPolicyVO.setItemCount1(itemStatisticsMap.get("1").getValue());
        }
        if (itemStatisticsMap.containsKey("2")) {
            normalPolicyVO.setItemCount2(itemStatisticsMap.get("2").getValue());
        }
        if (itemStatisticsMap.containsKey("3")) {
            normalPolicyVO.setItemCount3(itemStatisticsMap.get("3").getValue());
        }
        if (itemStatisticsMap.containsKey("4")) {
            normalPolicyVO.setItemCount4(itemStatisticsMap.get("4").getValue());
        }
        normalPolicyVO.setItemCount(normalPolicyVO.getItemCount1() + normalPolicyVO.getItemCount2() + normalPolicyVO.getItemCount3() + normalPolicyVO.getItemCount4());
        if (normalStatisticsMap.containsKey("1")) {
            normalPolicyVO.setNormalCount1(normalStatisticsMap.get("1").getValue());
        }
        if (normalStatisticsMap.containsKey("2")) {
            normalPolicyVO.setNormalCount2(normalStatisticsMap.get("2").getValue());
        }
        if (normalStatisticsMap.containsKey("3")) {
            normalPolicyVO.setNormalCount3(normalStatisticsMap.get("3").getValue());
        }
        if (normalStatisticsMap.containsKey("4")) {
            normalPolicyVO.setNormalCount4(normalStatisticsMap.get("4").getValue());
        }
        normalPolicyVO.setNormalCount(normalPolicyVO.getNormalCount1() + normalPolicyVO.getNormalCount2() + normalPolicyVO.getNormalCount3() + normalPolicyVO.getNormalCount4());
        normalPolicyVO.setNormalStatisticsList(normalStatisticsMap.values());
        normalPolicyVO.setItemStatisticsList(itemStatisticsMap.values());
        UserPlan userPlan = new UserPlan();
        userPlan.setUserId(user.getUserId());
        userPlan.setCompanyId(bo.getCompanyId());
        userPlan.setCompanyName(company.getName());
        userPlan.setRevenueScale(String.valueOf(bo.getRevenueScale()));
        userPlan.setCreateBy(String.valueOf(user.getUserId()));
        userPlan.setCreateTime(new Date());
        userPlan.setContent(JSONUtil.toJsonStr(normalPolicyVO));
        userPlan.setStatus("2");
        userPlanMapper.insert(userPlan);
        return normalPolicyVO;
    }

    private void policyIdHandler(List<ItemDataVO.ItemDataDetail> itemDataDetailList, Map<Long, ArticlePolicy> allPolicyMap, ArticlePolicy articlePolicy, Map<String, List<ArticlePolicy>> allParentPolicy) {

        if (Objects.nonNull(articlePolicy)) {
            ItemDataVO.ItemDataDetail itemDataDetail = new ItemDataVO.ItemDataDetail();
            itemDataDetail.setPolicyId(String.valueOf(articlePolicy.getArticleId()));
            itemDataDetail.setTitle(articlePolicy.getName());
            if (StrUtil.isNotBlank(articlePolicy.getItemGrade())) {
                itemDataDetail.setItemGrade(Integer.parseInt(articlePolicy.getItemGrade()));
            }
            itemDataDetailList.add(itemDataDetail);
            if (StrUtil.isNotBlank(articlePolicy.getParentId())) {
                long parentId = Long.parseLong(articlePolicy.getParentId());
                System.out.println(parentId);
                ArticlePolicy articlePolicy1 = allPolicyMap.get(parentId);
                System.out.println(articlePolicy1);
                policyIdHandler(itemDataDetailList, allPolicyMap, articlePolicy1, allParentPolicy);
            }
        }
    }

    private void statisticsMapConver(Map<String, ItemStatisticsVO> statisticsMap, Map<String, ItemStatisticsVO> childStatisticsMap) {

        for (Map.Entry<String, ItemStatisticsVO> item : statisticsMap.entrySet()) {
            if ("1".equals(item.getKey())) {
                item.getValue().setName("专项资金(" + item.getValue().getValue() + ")");
                List<ItemStatisticsVO> children = Lists.newArrayList();
                for (Map.Entry<String, ItemStatisticsVO> childStatistics : childStatisticsMap.entrySet()) {
                    if (childStatistics.getKey().startsWith("1")) {
                        childStatistics.getValue().setName(childStatistics.getValue().getName() + "(" + childStatistics.getValue().getValue() + ")");
                        children.add(childStatistics.getValue());
                    }
                }
                item.getValue().setChildren(children);
            } else if ("2".equals(item.getKey())) {
                item.getValue().setName("荣誉资质(" + item.getValue().getValue() + ")");
                List<ItemStatisticsVO> children = Lists.newArrayList();
                for (Map.Entry<String, ItemStatisticsVO> childStatistics : childStatisticsMap.entrySet()) {
                    if (childStatistics.getKey().startsWith("2")) {
                        childStatistics.getValue().setName(childStatistics.getValue().getName() + "(" + childStatistics.getValue().getValue() + ")");
                        children.add(childStatistics.getValue());
                    }
                }
                item.getValue().setChildren(children);
            } else if ("3".equals(item.getKey())) {
                item.getValue().setName("赛事活动(" + item.getValue().getValue() + ")");
                List<ItemStatisticsVO> children = Lists.newArrayList();
                for (Map.Entry<String, ItemStatisticsVO> childStatistics : childStatisticsMap.entrySet()) {
                    if (childStatistics.getKey().startsWith("3")) {
                        childStatistics.getValue().setName(childStatistics.getValue().getName() + "(" + childStatistics.getValue().getValue() + ")");
                        children.add(childStatistics.getValue());
                    }
                }
                item.getValue().setChildren(children);
            } else if ("4".equals(item.getKey())) {
                item.getValue().setName("其他(" + item.getValue().getValue() + ")");
                List<ItemStatisticsVO> children = Lists.newArrayList();
                for (Map.Entry<String, ItemStatisticsVO> childStatistics : childStatisticsMap.entrySet()) {
                    if (childStatistics.getKey().startsWith("4")) {
                        childStatistics.getValue().setName(childStatistics.getValue().getName() + "(" + childStatistics.getValue().getValue() + ")");
                        children.add(childStatistics.getValue());
                    }
                }
                item.getValue().setChildren(children);
            }
        }
    }

    private void statisticsMapHandler(Map<String, ItemStatisticsVO> statisticsMap, Map<String, ItemStatisticsVO> childStatisticsMap, ArticlePolicy policy, Map<String, List<ArticlePolicy>> allParentPolicy) {
        // 统计
        if (!allParentPolicy.containsKey(String.valueOf(policy.getArticleId()))) {
            if (Arrays.asList(new String[]{"1", "2", "3", "4"}).contains(policy.getItemType())) {
                ItemStatisticsVO itemStatisticsVO = statisticsMap.get(policy.getItemType());
                if (Objects.isNull(itemStatisticsVO)) {
                    itemStatisticsVO = new ItemStatisticsVO();
                }
                itemStatisticsVO.setName(policy.getItemType());
                itemStatisticsVO.setValue(itemStatisticsVO.getValue() + 1);
                statisticsMap.put(policy.getItemType(), itemStatisticsVO);
                if (StrUtil.isNotBlank(policy.getItemLevel())) {
                    ItemStatisticsVO childItemStatisticsVO = childStatisticsMap.get(policy.getItemType() + policy.getItemLevel());
                    if (Objects.isNull(childItemStatisticsVO)) {
                        childItemStatisticsVO = new ItemStatisticsVO();
                    }
                    switch (policy.getItemLevel()) {
                        case "1":
                            childItemStatisticsVO.setName("国家级");
                            break;
                        case "2":
                            childItemStatisticsVO.setName("省部级");
                            break;
                        case "3":
                            childItemStatisticsVO.setName("地市级");
                            break;
                        case "4":
                            childItemStatisticsVO.setName("区县级");
                            break;
                        case "5":
                            childItemStatisticsVO.setName("园区级");
                            break;
                        default:
                            break;
                    }

                    childItemStatisticsVO.setValue(childItemStatisticsVO.getValue() + 1);
                    childStatisticsMap.put(policy.getItemType() + policy.getItemLevel(), childItemStatisticsVO);
                }
            }
        }
    }

    // 前置政策逻辑判断
    private void preVerify(Company company, ArticlePolicy policy, Set<ArticlePolicy> allPolicyList, Map<Long, ArticlePolicy> allPolicyMap, Map<String, List<ArticlePolicy>> allParentPolicy, Map<Long, ArticlePolicy> prePolicyMap, List<String> preParentPolicyList) {

        // 只匹配出最后一级政策
        if (!allParentPolicy.containsKey(String.valueOf(policy.getArticleId()))) {
            // 判断是否有前置政策id
            if (StrUtil.isNotBlank(policy.getPrePolicyId())) {

                prePolicyRecursion(company, allPolicyMap, policy, prePolicyMap, preParentPolicyList);
            } else {
                // 没有前置条件(满足要求)添加到集合中
                if (!preParentPolicyList.contains(policy.getPrePolicyId() + "-" + String.valueOf(policy.getArticleId()))) {
                    allPolicyList.add(policy);
                }
            }
        }
    }

    private void preParentHandler(ArticlePolicy policy, Map<Long, ArticlePolicy> allPolicyMap, List<String> preParentPolicyList) {
        if (Objects.nonNull(policy)) {
            if (StrUtil.isNotBlank(policy.getPrePolicyId())) {
                String[] prePolicyIds = policy.getPrePolicyId().split(",");
                for (String prePolicyId : prePolicyIds) {
                    preParentPolicyList.add(prePolicyId + "-" + policy.getArticleId());
                    ArticlePolicy prePolicy = allPolicyMap.get(Long.parseLong(prePolicyId));
                    preParentHandler(prePolicy, allPolicyMap, preParentPolicyList);
                }
            }
        }
    }

    /**
     *  递归查询前置政策，直到前置有立项则返回；没有则直到找到最前置政策
     * @param company
     * @param allPolicyMap
     * @param policy
     * @param prePolicyMap
     * @param preParentPolicyList
     */
    private void prePolicyRecursion(Company company, Map<Long, ArticlePolicy> allPolicyMap, ArticlePolicy policy, Map<Long, ArticlePolicy> prePolicyMap, List<String> preParentPolicyList) {

        String[] prePolicyIds = policy.getPrePolicyId().split(",");
        for (String prePolicyId : prePolicyIds) {
            ArticlePolicy prePolicy = allPolicyMap.get(Long.parseLong(prePolicyId));
            if (Objects.isNull(prePolicy)) {
                continue;
            }
            if (Objects.nonNull(prePolicy.getPark1())) {
                if (!Objects.equals(prePolicy.getPark1(), company.getPark1())) {
                    continue;
                }
            }
            if (Objects.nonNull(prePolicy.getPark2())) {
                if (!Objects.equals(prePolicy.getPark2(), company.getPark2())) {
                    continue;
                }
            }
            if (Objects.nonNull(prePolicy.getPark3())) {
                if (!Objects.equals(prePolicy.getPark3(), company.getPark3())) {
                    continue;
                }
            }
            if (Objects.nonNull(prePolicy.getPark4())) {
                if (!Objects.equals(prePolicy.getPark4(), company.getPark4())) {
                    continue;
                }
            }
            if (Objects.nonNull(prePolicy.getPark5())) {
                if (!Objects.equals(prePolicy.getPark5(), company.getPark5())) {
                    continue;
                }
            }
            if (Objects.nonNull(prePolicy.getPark6())) {
                if (!Objects.equals(prePolicy.getPark6(), company.getPark6())) {
                    continue;
                }
            }

            SelectItemByPolicyBO query = new SelectItemByPolicyBO();
            query.setPolicyId(String.valueOf(prePolicy.getArticleId()));
            query.setCompanyNameList(company.getCompanyNameList());
            ExcelDetail excelDetail = excelDetailMapper.selectItemByPolicyAndCompany(query);
            // 没有年份间隔时间(满足要求)添加到集合中
            if (StrUtil.isBlank(policy.getPrePolicyYear())) {
                // 如果前置政策已有立项项目，将当前政策纳入规划
                if (Objects.nonNull(excelDetail)) {
                    if (!preParentPolicyList.contains(policy.getPrePolicyId() + "-" + policy.getArticleId())) {
                        prePolicyMap.put(policy.getArticleId(), policy);
                        preParentHandler(policy, allPolicyMap, preParentPolicyList);
                        return;
                    }
                } else {
                    if (!preParentPolicyList.contains(prePolicy.getPrePolicyId() + "-" + prePolicy.getArticleId())) {
                        prePolicyMap.put(prePolicy.getArticleId(), prePolicy);
                        preParentHandler(policy, allPolicyMap, preParentPolicyList);
                        if (prePolicyMap.containsKey(policy.getArticleId())) {
                            prePolicyMap.remove(policy.getArticleId());
                        }
                    }
                }
            } else {

                boolean flag = false;
                //  判断前置政策的年份间隔时间是否满足
                if (Objects.nonNull(excelDetail) && Objects.nonNull(excelDetail.getApprovalTime())) {
                    long intervalDay = DateUtil.betweenDay(new Date(), excelDetail.getApprovalTime(), true);
                    if (policy.getPrePolicyYear().contains("1")) {
                        if (intervalDay >= 0 && intervalDay <= 365) {
                            flag = true;
                        }
                    }
                    if (policy.getPrePolicyYear().contains("2")) {
                        if (intervalDay >= 365 && intervalDay <= 730) {
                            flag = true;
                        }
                    }
                    if (policy.getPrePolicyYear().contains("3")) {
                        if (intervalDay >= 730 && intervalDay <= 1095) {
                            flag = true;
                        }
                    }
                    if (policy.getPrePolicyYear().contains("4")) {
                        if (intervalDay >= 1095) {
                            flag = true;
                        }
                    }
                }
                if (flag) {
                    // 递归查询前置政策，直到前置有立项则返回；没有则直到找到最前置政策
                    // 如果前置政策已有立项项目，将当前政策纳入规划
                    if (Objects.nonNull(excelDetail)) {
                        if (!preParentPolicyList.contains(policy.getPrePolicyId() + "-" + policy.getArticleId())) {
                            prePolicyMap.put(policy.getArticleId(), policy);
                            preParentHandler(policy, allPolicyMap, preParentPolicyList);
                            return;
                        }
                    } else {
                        if (!preParentPolicyList.contains(prePolicy.getPrePolicyId() + "-" + prePolicy.getArticleId())) {
                            prePolicyMap.put(prePolicy.getArticleId(), prePolicy);
                            preParentHandler(policy, allPolicyMap, preParentPolicyList);
                            //  如果当前 前置政策数据存在前置政策，找到最前置政策，将最前置政策纳入规划
                            if (prePolicyMap.containsKey(policy.getArticleId())) {
                                prePolicyMap.remove(policy.getArticleId());
                            }
                        }
                    }
                }
            }
            if (StrUtil.isNotBlank(prePolicy.getPrePolicyId())) {
                prePolicyRecursion(company, allPolicyMap, prePolicy, prePolicyMap, preParentPolicyList);
            }
        }

    }

    private void expiresVerify(Company company, Map<String, Long> tagNamesMap, Set<ArticlePolicy> allPolicyList, ArticlePolicy articlePolicy, Map<Long, ArticlePolicy> allPolicyMap, Map<String, List<ArticlePolicy>> allParentPolicy, Map<Long, ArticlePolicy> prePolicyMap, List<String> preParentPolicyList) {

        if (!allParentPolicy.containsKey(String.valueOf(articlePolicy.getArticleId()))) {
            SelectItemByPolicyBO query = new SelectItemByPolicyBO();
            query.setPolicyId(String.valueOf(articlePolicy.getArticleId()));
            query.setCompanyNameList(company.getCompanyNameList());
            ExcelDetail excelDetail = excelDetailMapper.selectItemByPolicyAndCompany(query);
            //加入可再次申报立项结果里面有且已到再次申报执行期/有效期的
            if (Objects.nonNull(excelDetail) && "1".equals(articlePolicy.getIsRedeclaration())) {
                if (StrUtil.isNotBlank(articlePolicy.getTag()) && Objects.nonNull(excelDetail.getApprovalTime())) {
                    List<String> policyTagList = Arrays.asList(articlePolicy.getTag().split(","));
                    Long validityTagId1 = tagNamesMap.get("期限1");
                    Long validityTagId2 = tagNamesMap.get("期限2");
                    Long validityTagId3 = tagNamesMap.get("期限3");
                    Long validityTagId4 = tagNamesMap.get("期限4");
                    long betweenDay = DateUtil.betweenDay(excelDetail.getApprovalTime(), DateUtil.date(), true);
                    if (policyTagList.contains(String.valueOf(validityTagId1))) {
                        if (betweenDay >= (Integer.parseInt(configService.selectConfigByKey("expires1")) * 365L)) {
                            preVerify(company, articlePolicy, allPolicyList, allPolicyMap, allParentPolicy, prePolicyMap, preParentPolicyList);
                        }
                    } else if (policyTagList.contains(String.valueOf(validityTagId2))) {
                        if (betweenDay >= (Integer.parseInt(configService.selectConfigByKey("expires2")) * 365L)) {
                            preVerify(company, articlePolicy, allPolicyList, allPolicyMap, allParentPolicy, prePolicyMap, preParentPolicyList);
                        }
                    } else if (policyTagList.contains(String.valueOf(validityTagId3))) {
                        if (betweenDay >= (Integer.parseInt(configService.selectConfigByKey("expires3")) * 365L)) {
                            preVerify(company, articlePolicy, allPolicyList, allPolicyMap, allParentPolicy, prePolicyMap, preParentPolicyList);
                        }
                    } else if (policyTagList.contains(String.valueOf(validityTagId4))) {
                        if (betweenDay >= (Integer.parseInt(configService.selectConfigByKey("expires4")) * 365L)) {
                            preVerify(company, articlePolicy, allPolicyList, allPolicyMap, allParentPolicy, prePolicyMap, preParentPolicyList);
                        }
                    }
                }
            }
            // 不可再次申报但立项结果里面无立项记录的,可再次申报且立项结果里面无立项记录的
            else if (Objects.isNull(excelDetail)) {
                preVerify(company, articlePolicy, allPolicyList, allPolicyMap, allParentPolicy, prePolicyMap, preParentPolicyList);
            }
        }
    }

    private void manageHandler(Company company, Map<String, Long> tagNamesMap, ArticlePolicy articlePolicy, Set<ArticlePolicy> allPolicy, Map<Long, ArticlePolicy> allPolicyMap, Map<String, List<ArticlePolicy>> allParentPolicy, Map<Long, ArticlePolicy> prePolicyMap, List<String> preParentPolicyList) {
        // 2025-04-15 呈现方式table ，无 树结构关系，遍历每一层上级数据，进行匹配清理 返回
        // 地方管理、地方切换展示直至最上级的政策分类
        if ("6".equals(articlePolicy.getItemType()) || "7".equals(articlePolicy.getItemType())) {
            if (StrUtil.isBlank(articlePolicy.getManageRel())) {
                expiresVerify(company, tagNamesMap, allPolicy, articlePolicy, allPolicyMap, allParentPolicy, prePolicyMap, preParentPolicyList);
            } else {
                // 遍历每一层上级，将有效数据放入allParentPolicy
                articlePolicy.setParentId(articlePolicy.getManageRel());
                expiresVerify(company, tagNamesMap, allPolicy, articlePolicy, allPolicyMap, allParentPolicy, prePolicyMap, preParentPolicyList);
                ArticlePolicy manage1 = allPolicyMap.get(Long.parseLong(articlePolicy.getManageRel()));
                allParentPolicy.put(articlePolicy.getManageRel(), null);
                if (Objects.nonNull(manage1)) {
                    expiresVerify(company, tagNamesMap, allPolicy, manage1, allPolicyMap, allParentPolicy, prePolicyMap, preParentPolicyList);
                    if (StrUtil.isNotBlank(manage1.getManageRel())) {
                        manage1.setParentId(manage1.getManageRel());
                        ArticlePolicy manage2 = allPolicyMap.get(Long.parseLong(manage1.getManageRel()));
                        allParentPolicy.put(manage1.getManageRel(), null);
                        if (Objects.nonNull(manage2)) {
                            expiresVerify(company, tagNamesMap, allPolicy, manage2, allPolicyMap, allParentPolicy, prePolicyMap, preParentPolicyList);
                            if (StrUtil.isNotBlank(manage2.getManageRel())) {
                                manage2.setParentId(manage2.getManageRel());
                                ArticlePolicy manage3 = allPolicyMap.get(Long.parseLong(manage2.getManageRel()));
                                allParentPolicy.put(manage2.getManageRel(), null);
                                if (Objects.nonNull(manage3)) {
                                    expiresVerify(company, tagNamesMap, allPolicy, manage3, allPolicyMap, allParentPolicy, prePolicyMap, preParentPolicyList);
                                }
                            }
                        }
                    }
                }
//                if (Objects.nonNull(manage1)) {
//                    if (StrUtil.isBlank(manage1.getManageRel())) {
//                        expiresVerify(company, tagNamesMap, allPolicy, manage1, allPolicyMap, allParentPolicy, prePolicyMap, preParentPolicyList);
//                    } else {
//                        manage1.setParentId(manage1.getManageRel());
//                        ArticlePolicy manage2 = allPolicyMap.get(Long.parseLong(manage1.getManageRel()));
//                        if (Objects.nonNull(manage2)) {
//                            if (StrUtil.isBlank(manage2.getManageRel())) {
//                                expiresVerify(company, tagNamesMap, allPolicy, manage2, allPolicyMap, allParentPolicy, prePolicyMap, preParentPolicyList);
//                            } else {
//                                manage2.setParentId(manage2.getManageRel());
//                                ArticlePolicy manage3 = allPolicyMap.get(Long.parseLong(manage2.getManageRel()));
//                                if (Objects.nonNull(manage3)) {
//                                    expiresVerify(company, tagNamesMap, allPolicy, manage3, allPolicyMap, allParentPolicy, prePolicyMap, preParentPolicyList);
//                                }
//                            }
//                        }
//                    }
//                }
            }
        }
    }


    public List<UserPlan> getUserPlan() {
        SysUser user = getLoginUser().getUser();
        int rpc = 0;
        if (!SysUser.isAdmin(user.getUserId())) {
            WebAuthVo webAuthVo = webRoleAuthService.getAuthContent();
            rpc = Integer.parseInt(webAuthVo.getRpc());
        }

        return userPlanMapper.getUserPlan(rpc, user.getUserId());
    }

    public UserPlan getUserPlanDetail(Long id) {

        return userPlanMapper.selectById(id);
    }

    private void screenHandler(Map<String, Long> tagNamesMap, Company company, NormalPolicyBO bo) {

        String identifier = company.getIdentifier();
        String companyName = company.getName().trim();
        Integer cbrs = company.getCbrs();
        String foundingDate = company.getFoundingDate();
        List<String> tagIds = Lists.newArrayList();

        List<String> industryList = Arrays.asList((company.getIndustryName1() + "," + company.getIndustryName2() + "," + company.getIndustryName3() + "," + company.getIndustryName4()).split(","));

        // 单位类别标签
        if (StrUtil.isNotBlank(identifier)) {
            String prefix = identifier.trim().substring(0, 2);
            if ("11".equals(prefix) && companyName.endsWith("人民政府")) {
                Long tagId = tagNamesMap.get("地方政府");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            } else if ("11".equals(prefix) && !companyName.endsWith("人民政府")) {
                Long tagId = tagNamesMap.get("内设机构");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            } else if ("11".equals(prefix)) {
                Long tagId = tagNamesMap.get("机关");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            } else if ("12".equals(prefix) && companyName.endsWith("医院")) {
                Long tagId = tagNamesMap.get("公办医院");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            } else if ("12".equals(prefix) && (companyName.endsWith("大学") || companyName.endsWith("学院") || companyName.endsWith("职业技术学院") || companyName.endsWith("职业学院") || companyName.endsWith("高等专科学") || companyName.endsWith("职业技术大学") || companyName.endsWith("职业大学"))) {
                Long tagId = tagNamesMap.get("公办高校");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            } else if ("12".equals(prefix) && companyName.endsWith("中学")) {
                Long tagId = tagNamesMap.get("公办中学");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            } else if ("12".equals(prefix) && companyName.endsWith("小学")) {
                Long tagId = tagNamesMap.get("公办小学");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            } else if ("12".equals(prefix) && (companyName.endsWith("科学院") || companyName.endsWith("科学技术中心") || companyName.endsWith("研究院") || companyName.endsWith("研究所"))) {
                Long tagId = tagNamesMap.get("公办科研机构");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            } else if ("12".equals(prefix) && companyName.endsWith("管理委员会")) {
                Long tagId = tagNamesMap.get("园区管委会");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            } else if ("12".equals(prefix)) {
                Long tagId = tagNamesMap.get("事业单位");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            } else if ("51".equals(prefix) && companyName.endsWith("协会")) {
                Long tagId = tagNamesMap.get("协会");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            } else if ("51".equals(prefix) && companyName.endsWith("学会")) {
                Long tagId = tagNamesMap.get("学会");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            } else if ("51".equals(prefix) && companyName.endsWith("研究会")) {
                Long tagId = tagNamesMap.get("研究会");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            } else if ("51".equals(prefix) && companyName.endsWith("战略联盟")) {
                Long tagId = tagNamesMap.get("战略联盟");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            } else if ("51".equals(prefix)) {
                Long tagId = tagNamesMap.get("社会团体");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            } else if ("52".equals(prefix) && companyName.endsWith("医院")) {
                Long tagId = tagNamesMap.get("民办医院");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            } else if ("52".equals(prefix) && (companyName.endsWith("大学") || companyName.endsWith("学院") || companyName.endsWith("职业技术学院") || companyName.endsWith("职业学院") || companyName.endsWith("高等专科学") || companyName.endsWith("职业技术大学") || companyName.endsWith("职业大学"))) {
                Long tagId = tagNamesMap.get("民办高校");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            } else if ("52".equals(prefix) && companyName.endsWith("中学")) {
                Long tagId = tagNamesMap.get("民办中学");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            } else if ("52".equals(prefix) && companyName.endsWith("小学")) {
                Long tagId = tagNamesMap.get("民办小学");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            } else if ("52".equals(prefix) && (companyName.endsWith("科学院") || companyName.endsWith("科学技术中心") || companyName.endsWith("研究院") || companyName.endsWith("研究所"))) {
                Long tagId = tagNamesMap.get("民办科研机构");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            } else if ("52".equals(prefix)) {
                Long tagId = tagNamesMap.get("民办非企业");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            } else if ("91".equals(prefix) && !industryList.contains("72商务服务业") && !industryList.contains("74专业技术服务业") && !industryList.contains("75科技推广和应用服务业")) {
                Long tagId = tagNamesMap.get("常规企业");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            } else if ("91".equals(prefix) && industryList.contains("72商务服务业") || industryList.contains("74专业技术服务业") || industryList.contains("75科技推广和应用服务业")) {
                Long tagId = tagNamesMap.get("科技服务企业");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            } else if ("91".equals(prefix)) {
                Long tagId = tagNamesMap.get("企业");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            } else if ("92".equals(prefix)) {
                Long tagId = tagNamesMap.get("个体户");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            } else if ("93".equals(prefix)) {
                Long tagId = tagNamesMap.get("农民专业合作社");
                if (Objects.nonNull(tagId)) {
                    tagIds.add(String.valueOf(tagId));
                }
            }
        }

        if (tagIds.contains("874") || tagIds.contains("875") || tagIds.contains("876")) {

            // 人员规模
            if (Objects.nonNull(cbrs)) {
                if (cbrs < Integer.parseInt(configService.selectConfigByKey("personnel_size1"))) {
                    Long tagId = tagNamesMap.get("人员规模1");
                    if (Objects.nonNull(tagId)) {
                        tagIds.add(String.valueOf(tagId));
                    }
                } else if (cbrs < Integer.parseInt(configService.selectConfigByKey("personnel_size2"))) {
                    Long tagId = tagNamesMap.get("人员规模2");
                    if (Objects.nonNull(tagId)) {
                        tagIds.add(String.valueOf(tagId));
                    }
                } else if (cbrs < Integer.parseInt(configService.selectConfigByKey("personnel_size3"))) {
                    Long tagId = tagNamesMap.get("人员规模3");
                    if (Objects.nonNull(tagId)) {
                        tagIds.add(String.valueOf(tagId));
                    }
                } else if (cbrs < Integer.parseInt(configService.selectConfigByKey("personnel_size4"))) {
                    Long tagId = tagNamesMap.get("人员规模4");
                    if (Objects.nonNull(tagId)) {
                        tagIds.add(String.valueOf(tagId));
                    }
                } else if (cbrs < Integer.parseInt(configService.selectConfigByKey("personnel_size5"))) {
                    Long tagId = tagNamesMap.get("人员规模5");
                    if (Objects.nonNull(tagId)) {
                        tagIds.add(String.valueOf(tagId));
                    }
                } else if (cbrs < Integer.parseInt(configService.selectConfigByKey("personnel_size6"))) {
                    Long tagId = tagNamesMap.get("人员规模6");
                    if (Objects.nonNull(tagId)) {
                        tagIds.add(String.valueOf(tagId));
                    }
                } else {
                    Long tagId = tagNamesMap.get("人员规模7");
                    if (Objects.nonNull(tagId)) {
                        tagIds.add(String.valueOf(tagId));
                    }
                }
            }

            // 成立时间
            if (StrUtil.isNotBlank(foundingDate)) {
                long betweenDay = DateUtil.betweenDay(DateUtil.parseDate(foundingDate), DateUtil.date(), true);
                if (betweenDay < Integer.parseInt(configService.selectConfigByKey("regtime1"))) {
                    Long tagId = tagNamesMap.get("成立时间1");
                    if (Objects.nonNull(tagId)) {
                        tagIds.add(String.valueOf(tagId));
                    }
                } else if (betweenDay < Integer.parseInt(configService.selectConfigByKey("regtime2"))) {
                    Long tagId = tagNamesMap.get("成立时间2");
                    if (Objects.nonNull(tagId)) {
                        tagIds.add(String.valueOf(tagId));
                    }
                } else if (betweenDay < Integer.parseInt(configService.selectConfigByKey("regtime3"))) {
                    Long tagId = tagNamesMap.get("成立时间3");
                    if (Objects.nonNull(tagId)) {
                        tagIds.add(String.valueOf(tagId));
                    }
                } else if (betweenDay < Integer.parseInt(configService.selectConfigByKey("regtime4"))) {
                    Long tagId = tagNamesMap.get("成立时间4");
                    if (Objects.nonNull(tagId)) {
                        tagIds.add(String.valueOf(tagId));
                    }
                } else {
                    Long tagId = tagNamesMap.get("成立时间5");
                    if (Objects.nonNull(tagId)) {
                        tagIds.add(String.valueOf(tagId));
                    }
                }
            }

            // 收入规模
            BigDecimal revenueScale = bo.getRevenueScale();
            if (Objects.nonNull(revenueScale)) {
                if (revenueScale.compareTo(BigDecimal.ZERO) <= 0) {
                    Long tagId = tagNamesMap.get("收入规模1");
                    if (Objects.nonNull(tagId)) {
                        tagIds.add(String.valueOf(tagId));
                    }
                } else if (revenueScale.compareTo(new BigDecimal("0")) >= 0 && revenueScale.compareTo(new BigDecimal("300")) < 0) {
                    Long tagId = tagNamesMap.get("收入规模2");
                    if (Objects.nonNull(tagId)) {
                        tagIds.add(String.valueOf(tagId));
                    }
                } else if (revenueScale.compareTo(new BigDecimal("300")) >= 0 && revenueScale.compareTo(new BigDecimal("1000")) < 0) {
                    Long tagId = tagNamesMap.get("收入规模3");
                    if (Objects.nonNull(tagId)) {
                        tagIds.add(String.valueOf(tagId));
                    }
                } else if (revenueScale.compareTo(new BigDecimal("1000")) >= 0 && revenueScale.compareTo(new BigDecimal("2000")) < 0) {
                    Long tagId = tagNamesMap.get("收入规模4");
                    if (Objects.nonNull(tagId)) {
                        tagIds.add(String.valueOf(tagId));
                    }
                } else if (revenueScale.compareTo(new BigDecimal("2000")) >= 0 && revenueScale.compareTo(new BigDecimal("3000")) < 0) {
                    Long tagId = tagNamesMap.get("收入规模5");
                    if (Objects.nonNull(tagId)) {
                        tagIds.add(String.valueOf(tagId));
                    }
                } else if (revenueScale.compareTo(new BigDecimal("3000")) >= 0 && revenueScale.compareTo(new BigDecimal("5000")) < 0) {
                    Long tagId = tagNamesMap.get("收入规模6");
                    if (Objects.nonNull(tagId)) {
                        tagIds.add(String.valueOf(tagId));
                    }
                } else if (revenueScale.compareTo(new BigDecimal("5000")) >= 0 && revenueScale.compareTo(new BigDecimal("10000")) < 0) {
                    Long tagId = tagNamesMap.get("收入规模7");
                    if (Objects.nonNull(tagId)) {
                        tagIds.add(String.valueOf(tagId));
                    }
                } else if (revenueScale.compareTo(new BigDecimal("10000")) >= 0 && revenueScale.compareTo(new BigDecimal("20000")) < 0) {
                    Long tagId = tagNamesMap.get("收入规模8");
                    if (Objects.nonNull(tagId)) {
                        tagIds.add(String.valueOf(tagId));
                    }
                } else if (revenueScale.compareTo(new BigDecimal("20000")) >= 0 && revenueScale.compareTo(new BigDecimal("30000")) < 0) {
                    Long tagId = tagNamesMap.get("收入规模9");
                    if (Objects.nonNull(tagId)) {
                        tagIds.add(String.valueOf(tagId));
                    }
                } else if (revenueScale.compareTo(new BigDecimal("30000")) >= 0 && revenueScale.compareTo(new BigDecimal("50000")) < 0) {
                    Long tagId = tagNamesMap.get("收入规模10");
                    if (Objects.nonNull(tagId)) {
                        tagIds.add(String.valueOf(tagId));
                    }
                } else {
                    Long tagId = tagNamesMap.get("收入规模11");
                    if (Objects.nonNull(tagId)) {
                        tagIds.add(String.valueOf(tagId));
                    }
                }
            }
        }
        bo.setTagIds(tagIds);
    }

    public Long saveUserPlan(UserPlan userPlan) {
        SysUser user = getLoginUser().getUser();
        userPlan.setCompanyName(userPlan.getCompanyName());
        userPlan.setUserId(user.getUserId());
        userPlan.setCreateBy(String.valueOf(user.getUserId()));
        userPlan.setCreateTime(new Date());
        userPlan.setStatus("1");
        if (Objects.nonNull(userPlan.getId())) {
            userPlanMapper.updateById(userPlan);
        } else {
            userPlanMapper.insert(userPlan);
        }
        return userPlan.getId();
    }

//    @Override
//    public NormalPolicyVO normalPolicy(NormalPolicyBO bo) {
//        NormalPolicyVO normalPolicyVO = new NormalPolicyVO();
//        List<ExcelDetail> excelDetailList = Lists.newArrayList();
//        SysUser user = getLoginUser().getUser();
//
//        // 所有主管部门
//        List<OrgInfo> orgList = orgInfoMapper.selectList(Wrappers.<OrgInfo>lambdaQuery().select(OrgInfo::getOrgId, OrgInfo::getType, OrgInfo::getOrgName, OrgInfo::getParentOrgId).eq(OrgInfo::getIsDeleted, "0"));
//        Map<Long, OrgInfo> orgMap = orgList.stream().collect(Collectors.toMap(OrgInfo::getOrgId, x -> x));
//
//        // 主管类型数据
//        List<SysDictData> sysDictDataList = dictTypeService.selectDictDataByType("org_type");
//        Map<String, Long> orgTypeMap = sysDictDataList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictSort));
//
//        List<ArticlePolicy> policyList = articlePolicyMapper.getAllPolicy(new ArticlePolicy());
//        // 所有政策Map
//        Map<Long, ArticlePolicy> allPolicyMap = policyList.stream().filter(item -> "1".equals(item.getStatus())).collect(Collectors.toMap(ArticlePolicy::getArticleId, x -> x));
//        // 所有父级政策
//        Map<String, List<ArticlePolicy>> allParentPolicy = policyList.stream().filter(item -> StrUtil.isNotBlank(item.getParentId())).collect(Collectors.groupingBy(ArticlePolicy::getParentId));
//
//        // 前置政策Map
//        Map<Long, ArticlePolicy> prePolicyMap = new HashMap();
//        // 前置父级政策集合
//        List<String> preParentPolicyList = Lists.newArrayList();
//        if (!SysUser.isAdmin(user.getUserId())) {
//            WebAuthVo webAuthVo = webRoleAuthService.getAuthContent();
//            int pc = Integer.parseInt(webAuthVo.getPc());
//            String createTime = DateUtil.formatDate(DateUtil.offsetDay(new Date(), -90));
//            int count = userPlanMapper.getPlanCount(createTime, user.getUserId());
//            if (pc - count <= 0) {
//                throw new ServiceException("当前规划次数本季度内已达上线，开通更高级别会员可获得更多权益");
//            }
//        }
//
//        Company company = null;
//        if (bo.getCompanyId() == 0L) {
//            company = companyService.getQccCompany(bo.getCompanyName());
//        } else {
//            company = companyMapper.selectById(bo.getCompanyId());
//            if (Objects.nonNull(company)) {
//                if (company.getGetApi() != 1L) {
//                    company = companyService.getQccCompany(company.getName());
//                }
//            }
//        }
//        if (StrUtil.isNotBlank(company.getParkAreaId())) {
//            List<ParkArea> parkAreaList = parkAreaMapper.selectList(Wrappers.<ParkArea>lambdaQuery());
//            Map<Long, String> parkAreaMap = parkAreaList.stream().collect(Collectors.toMap(ParkArea::getId, ParkArea::getName));
//            List<String> parkAreaIdList = Arrays.asList(company.getParkAreaId().split(","));
//            List<String> parkAreaNameList = new ArrayList<>();
//            for (String parkAreaId : parkAreaIdList) {
//                if (!"null".equals(parkAreaId)) {
//                    parkAreaNameList.add(parkAreaMap.get(Long.parseLong(parkAreaId)));
//                }
//            }
//            company.setParkAreaName(String.join("-", parkAreaNameList));
//        }
//        normalPolicyVO.setCompany(company);
//
//        List<String> companyNameList = Lists.newArrayList();
//        companyNameList.add(company.getName());
//        // 根据单位名称（含：曾用名），在平台“项目立项数据库”中查询，查询该单位已立项项目信息
//        if (StrUtil.isNotBlank(company.getHistoryName())) {
//            String[] companyNames = company.getHistoryName().split(";");
//            for (String companyName : companyNames) {
//                if (StrUtil.isNotBlank(companyName) && !"无".equals(companyName)) {
//                    if (companyName.contains("（")) {
//                        companyName = companyName.substring(0, companyName.indexOf("（"));
//                        companyNameList.add(companyName);
//                    }
//                }
//            }
//        }
//        bo.setCompanyNameList(companyNameList);
//        company.setCompanyNameList(companyNameList);
//
//        ServiceException.throwExOnCondition(Objects.isNull(company), "未查询到对应企业数据");
//
//        // 地区范围处理
//        if (StrUtil.isNotBlank(company.getParkAreaId())) {
//            bo.setAreaIds(Arrays.asList(company.getParkAreaId().split(",")));
//        }
//        parkAreaHandler(bo);
//
//        if (Objects.nonNull(company.getIndustry4())) {
//            bo.setIndustryId("," + company.getIndustry4());
//        }
//
//        // 标签处理
//        List<Tag> tagList = tagMapper.selectList(Wrappers.lambdaQuery());
//        Map<String, Long> tagNamesMap = tagList.stream().collect(Collectors.toMap(Tag::getName, Tag::getId));
//        screenHandler(tagNamesMap, company, bo);
//        List<ArticlePolicy> articlePolicyList = articlePolicyMapper.normalPolicy(bo);
//        // 排重List
//        List<Long> articleIds = Lists.newArrayList();
//        if (CollUtil.isNotEmpty(articlePolicyList)) {
//            articleIds = articlePolicyList.stream().map(ArticlePolicy::getArticleId).collect(Collectors.toList());
//        }
//        // 根据“单位类别标签”、“成立时间标签”、“所属地区”（项目类别覆盖范围）、“所属园区”（项目类别覆盖范围）、“所属行业标签”、“收入规模标签”、“人员规模标签”与“项目状态标签”为“现行有效”的项目类别进行匹配
//        Set<ArticlePolicy> allPolicyList = new HashSet<>();
//        Map<String, ItemStatisticsVO> normalStatisticsMap = new HashMap<>();
//        Map<String, ItemStatisticsVO> childNormalStatisticsMap = new HashMap<>();
//        for (ArticlePolicy articlePolicy : articlePolicyList) {
//
//            if (!Arrays.asList("1", "2", "3", "4").contains(articlePolicy.getItemType())) {
//                // 地方管理、地方切块切换至最高级
//                manageHandler(company, tagNamesMap, articlePolicy, allPolicyList, allPolicyMap, allParentPolicy, prePolicyMap, preParentPolicyList);
//            } else {
//                // 有效期期限判断
//                expiresVerify(company, tagNamesMap, allPolicyList, articlePolicy, allPolicyMap, allParentPolicy, prePolicyMap, preParentPolicyList);
//            }
//        }
//
//
//        List<ArticlePolicy> approvalPolicyList = articlePolicyMapper.getApprovalPolicy(bo);
//
//        Map<String, ItemStatisticsVO> itemStatisticsMap = new HashMap<>();
//        Map<String, ItemStatisticsVO> childItemStatisticsMap = new HashMap<>();
//        for (ArticlePolicy articlePolicy : approvalPolicyList) {
//            if (!Arrays.asList("1", "2", "3", "4").contains(articlePolicy.getItemType())) {
//                // 地方管理、地方切块切换至最高级
//                manageHandler(company, tagNamesMap, articlePolicy, allPolicyList, allPolicyMap, allParentPolicy, prePolicyMap, preParentPolicyList);
//            } else if ("1".equals(articlePolicy.getItemType())) {
//                // 有效期期限判断
//                expiresVerify(company, tagNamesMap, allPolicyList, articlePolicy, allPolicyMap, allParentPolicy, prePolicyMap, preParentPolicyList);
//            }
//
//            // 立项政策(荣誉资质、赛事活动、其他)关联的政策(专项资金)钠入规划（获得时间为1年内）
//            else if ("2".equals(articlePolicy.getItemType()) || "3".equals(articlePolicy.getItemType()) || "4".equals(articlePolicy.getItemType())) {
//                if (StrUtil.isNotBlank(articlePolicy.getConnection())) {
//                    String[] connectionIds = articlePolicy.getConnection().split(",");
//                    bo.setConnectionIds(Arrays.asList(connectionIds));
//                    if (connectionIds.length > 0) {
//                        // 查询关联政策
//                        List<ArticlePolicy> connectionPolicyList = articlePolicyMapper.getConnectionPolicy(bo);
//                        for (ArticlePolicy policy : connectionPolicyList) {
//                            if (!articleIds.contains(policy.getArticleId())) {
//                                SelectItemByPolicyBO query = new SelectItemByPolicyBO();
//                                query.setPolicyId(String.valueOf(policy.getArticleId()));
//                                query.setCompanyNameList(company.getCompanyNameList());
//                                ExcelDetail excelDetail = excelDetailMapper.selectItemByPolicyAndCompany(query);
//                                if (Objects.nonNull(excelDetail)) {
//                                    long betweenDay = DateUtil.betweenDay(excelDetail.getApprovalTime(), DateUtil.date(), true);
//                                    if (betweenDay <= 365) {
//                                        expiresVerify(company, tagNamesMap, allPolicyList, policy, allPolicyMap, allParentPolicy, prePolicyMap, preParentPolicyList);
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//        }
//
//        // 最终处理结果Map
//        TreeMap<Long, ArticlePolicy> policyResultMap = new TreeMap<>();
//
//        // 将前置政策加入规划
//        for (Map.Entry<Long, ArticlePolicy> item : prePolicyMap.entrySet()) {
//            allPolicyList.add(item.getValue());
//        }
//
//        // 查询每个政策的树结构(最多5层结构) 查找逻辑：上找4层，下找4层
//        findPolicyParentRel(allPolicyList, policyResultMap, allPolicyMap, allParentPolicy);
//
//
//        normalPolicyVO.setNormalCount(normalPolicyVO.getNormalCount1() + normalPolicyVO.getNormalCount2() + normalPolicyVO.getNormalCount3() + normalPolicyVO.getNormalCount4());
//        normalPolicyVO.setNormalStatisticsList(normalStatisticsMap.values());
//        normalPolicyVO.setItemStatisticsList(itemStatisticsMap.values());
//        return normalPolicyVO;
//    }

}
